如何在计算属性更改时触发 Vue 方法
本质上,在 Vue 应用程序中,我有一个列出联系人的页面。以及作为标题组件一部分的搜索表单。我将输入搜索项捕获为 vuex 存储中的状态变量,并将其作为计算变量进行跟踪。
我有一种方法来检索在已安装的挂钩中调用的联系人。每当状态搜索变量发生变化时,我想再次调用相同的 getContacts 方法。使用观察者来执行此 atm,但我读到观察计算值不是正确的方法。想知道是否有更好的方法来做到这一点。下面的脚本。
<script>
import API from '@/utils/Api.js'
...
export default ({
...
tableData: [],
}
},
computed: {
search() {
return this.$store.getters.search;
}
},
mounted() {
this.getContacts();
},
methods: {
async getContacts() {
try {
const {data} = await API.get('/contacts?search=' + this.search)
this.tableData = data
} catch (e) {
console.error(e)
}
}
},
watch: {
search () {
this.getContacts();
}
}
})
</script>
Essentially, in a Vue application, I have a page that lists Contacts. And a search form that is part of a header component. I capture the input search term as a state variable in the vuex store and track it as a computed variable.
I have a method to retrieve contacts that is called within the mounted hook. I want to call the same getContacts method again whenever the state search variable changes. Using a watcher to do this atm, but I have read that watching a computed value is not the right way. Wondering if there is a better way to do this. Script below.
<script>
import API from '@/utils/Api.js'
...
export default ({
...
tableData: [],
}
},
computed: {
search() {
return this.$store.getters.search;
}
},
mounted() {
this.getContacts();
},
methods: {
async getContacts() {
try {
const {data} = await API.get('/contacts?search=' + this.search)
this.tableData = data
} catch (e) {
console.error(e)
}
}
},
watch: {
search () {
this.getContacts();
}
}
})
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试直接监视状态项,然后将新值作为方法的参数传递,然后使用
immediate:true
替换已安装的钩子调用:Try to watch directly the state item and then pass the new value as parameter for the method, then use
immediate:true
to replace the mounted hook call :