使用 SFC 在 Vue 中编辑表单

Edit form in Vue with SFC

我想创建一个编辑表单,使用 fetch 使用 API 中的现有数据填充表单,然后让用户编辑表单并将表单数据提交到 API 使用 PUT 请求。

要求:

这是我的代码,但我还没有完全弄清楚。

<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>

您可以 test/experiment 使用我的代码 https://stackblitz.com/edit/vitejs-vite-iyy2pu?file=src%2Fcomponents%2FUserProfile.vue&terminal=dev

我知道怎么做了。

我使用 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>