【发布时间】:2021-11-08 07:08:21
【问题描述】:
我从 API 获取数据,我用这些数据在我的组件中填充表单。我只需要在初始填充数据后触发观察者。就像以异步方式一样。但是观察者会立即被触发。只有在初始填充数据后更改了任何值时,我才需要禁用更新按钮。
<template>
<div id="app">
<input type="text" v-model="user.userId" /> <br />
<br />
<input type="text" v-model="user.title" /> <br />
<br />
<button :disabled="isDisabled">Update</button>
</div>
</template>
<script>
export default {
name: "App",
watch: {
user: {
handler(oldVal, newVal) {
if (oldVal != newVal) {
this.isLoaded = false;
}
},
deep: true,
},
},
computed: {
isDisabled() {
return this.isLoaded;
},
},
async created() {
await fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json())
.then((json) => {
this.user = json;
this.isLoaded = true;
});
},
data() {
return {
user: {
userId: 0,
id: 0,
title: "",
completed: false,
},
isLoaded: true,
};
},
};
</script>
我已经推荐了Vue, await for Watch 和Are watches asynchronous? 和Vue.js How to watcher before mounted() , can't get data from watch,但我无法关注。
这是一个预览:https://codesandbox.io/embed/great-euler-skd3v?fontsize=14&hidenavigation=1&theme=dark
【问题讨论】:
标签: javascript vue.js