0๐
โ
I figured out how to do this.
I use ref
not reactive
, and have to put the async fetch(...)
code inside 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>
Source:stackexchange.com