我想創建一個編輯表單,使用來自 API 的現有資料填充表單fetch,然后讓用戶編輯表單并使用 PUT 請求將表單資料提交給 API。
要求:
- 組合 API不是選項 API
- 單檔案組件 SFC 與
<script setup>not<script> async/await語法不使用決議承諾.then()- 打字稿
這是我的代碼,但我還沒有完全弄清楚。
<script setup lang="ts">
import { ref, reactive } from 'vue'; // ref or reactive?
interface Profile {
firstName: string;
lastName: string;
}
const profile = reactive<Profile | null>(null); // initial state is null before we fetch?
//profile.value = await fakeFetch(); // after fetch we need to update the state
function onSubmit() {
alert(JSON.stringify(profile));
}
function fakeFetch(): Promise<Profile> {
const data: Profile = {
firstName: 'Alice',
lastName: 'Smith',
};
return new Promise(resolve => resolve(data));
}
</script>
<template>
<h1>Your user profile</h1>
<p v-if="profile">You have a profile</p>
<p v-else>The profile does not exist</p>
<!-- v-if="profile" because profile is null before fetch has finished? -->
<form @submit.prevent="onSubmit" v-if="profile">
<input type="text" v-model="profile.firstName" />
<input type="text" v-model="profile.lastName" />
<input type="submit" value="Update" />
</form>
</template>
您可以在https://stackblitz.com/edit/vitejs-vite-iyy2pu?file=src/components/UserProfile.vue&terminal=dev使用我的代碼進行測驗/實驗
uj5u.com熱心網友回復:
我想出了如何做到這一點。
我用的ref不是reactive,必須把async fetch(...)代碼放在里面onMounted。
<script setup lang="ts">
import { ref, onMounted } from 'vue';
interface Post {
firstName: string;
lastName: string;
}
const profile = ref<Post | null>(null);
onMounted(async () => {
const data = await fakeFetch();
profile.value = data;
});
function onSubmit() {
alert(JSON.stringify(profile.value));
}
function fakeFetch(): Promise<Post> {
const data: Post = {
firstName: 'Alice',
lastName: 'Smith',
};
return new Promise(resolve => resolve(data));
}
</script>
<template>
<h1>Your user profile</h1>
<p v-if="profile">You have a profile</p>
<p v-else>The profile does not exist</p>
<form @submit.prevent="onSubmit" v-if="profile">
<input type="text" v-model="profile.firstName" />
<input type="text" v-model="profile.lastName" />
<input type="submit" value="Update" />
</form>
</template>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/442952.html
標籤:Vue.js Vuejs3 vue-composition-api Vue-sfc
上一篇:即使沒有設定身份驗證計劃,也無法使用Postman訪問Sqlitedb
下一篇:VueJS字串化路由
