在 Vue.js 中,我们经常需要监听异步数据的变化。这些数据可能来自于后端接口、浏览器本地存储或其他第三方库。Vue.js 提供了 watch 属性来监听数据的变化,但是在监听异步数据时,我们需要使用一些特殊的技巧来确保监听器能够正确地工作。
1. 使用 deep 属性
在 Vue.js 中,watch 属性默认只监听对象的第一层属性。如果我们需要监听对象深层嵌套的属性,需要使用 deep 属性。例如:
watch: {
'user.name': {
handler: function (newVal, oldVal) {
console.log('user.name changed')
},
deep: true
}
}在上面的例子中,我们监听了 user 对象的 name 属性。由于 name 属性是嵌套在 user 对象中的,我们需要使用 deep 属性来确保监听器能够正确地工作。
2. 使用 immediate 属性
在 Vue.js 中,watch 属性默认不会在组件初始化时触发监听器。如果我们需要在组件初始化时立即执行监听器,需要使用 immediate 属性。例如:
watch: {
'user.name': {
handler: function (newVal, oldVal) {
console.log('user.name changed')
},
immediate: true
}
}在上面的例子中,我们监听了 user 对象的 name 属性,并且在组件初始化时立即执行监听器。
3. 使用 $watch 方法
在 Vue.js 中,我们还可以使用 $watch 方法来监听异步数据的变化。$watch 方法有两个参数:要监听的属性和回调函数。例如:
this.$watch('user.name', function (newVal, oldVal) {
console.log('user.name changed')
})与 watch 属性不同,$watch 方法可以在组件销毁时自动取消监听器,从而避免内存泄漏。
4. 使用 Promise 和 async/await
在 Vue.js 中,我们经常使用 Promise 和 async/await 来处理异步数据。如果我们需要监听 Promise 或 async/await 返回的数据,可以使用 $watch 方法并在回调函数中使用 async/await。例如:
this.$watch('userPromise', async function (newVal, oldVal) {
const user = await newVal
console.log('userPromise changed', user)
})在上面的例子中,我们监听了一个返回 Promise 的 userPromise 属性,并在回调函数中使用 async/await 处理 Promise 返回的数据。
示例代码
下面是一个完整的示例代码,演示了如何在 Vue.js 中监听异步数据的变化:
// www.javascriptcn.com code example
<template>
<div>
<p>User name: {{ user.name }}</p>
<p>User age: {{ user.age }}</p>
</div>
</template>
<script>
export default {
data () {
return {
userPromise: getUser(),
user: {}
}
},
watch: {
'user.name': {
handler: function (newVal, oldVal) {
console.log('user.name changed')
},
deep: true
},
immediate: true
},
methods: {
async getUser () {
const response = await fetch('/user')
const user = await response.json()
return user
}
},
async created () {
this.user = await this.userPromise
}
}
</script>在上面的代码中,我们定义了一个 User 组件,并在组件初始化时获取用户数据。我们使用了 $watch 方法来监听 userPromise 属性,并在回调函数中使用 async/await 处理 Promise 返回的数据。我们还使用了 watch 属性来监听 user 对象的 name 属性,并在组件初始化时立即执行监听器。最后,我们在 created 钩子函数中将获取的用户数据赋值给 user 对象,以便在模板中显示。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d5617fa941bf7134a00e55