javascript - 如何仅在 VueJS 中的 API 初始加载后观看?
问题描述
我从 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,等待 Watch和手表是异步的吗?和Vue.js How to watcher before mounted() ,无法从手表获取数据,但我无法关注。
这是一个预览:https ://codesandbox.io/embed/great-euler-skd3v?fontsize=14&hidenavigation=1&theme=dark
解决方案
这需要通过一些条件来确定。
isLoaded
已经服务于确定初始加载状态的目的,但名称令人困惑,因为它确定数据未加载。
有可能:
watch: {
user: {
if (this.isLoading && oldVal != newVal) {
this.isLoading = false;
}
...
观察者不需要deep
并且在不需要时可以不被观察:
async created() {
let unwatchUser = this.$watch('user', (oldVal, newVal) => {
if (this.isLoading && oldVal != newVal) {
this.isLoading = false;
unwatchUser();
}
})
...
指定数据尚未加载的常用方法是将其设置为null
,即无值。这不需要isLoading
标志或观察者。如果null
由于引用的对象属性而不需要,则可以通过可选的链接和条件渲染来克服:
<div v-if="user">
<input type="text" v-model="user.userId" />
...
<div v-else class="spinner"/>
推荐阅读
- c# - UWP NavigationView 的模板选择器
- python - Python创建一个以唯一日期列表为索引的新数据框
- java - IntelliJ Spring 在 .xml 文件中声明基包和类
- sql - 按参数将数据放入范围
- javascript - 创建后更新 Apollo 客户端身份验证链接
- python - Python Tkinter 如何使文本框滚动
- php - Symfony 4 登录访问:没有数据持久性
- logstash - Grok - 用不同长度的行解析日志
- regex - 使用 ListFile 获取文件,但按其中包含日期的名称进行过滤
- ios - 接收 JSON 数据但没有打印任何内容(Swift)?