Gre*_*nov 4 watch destroy vuejs2
我怎么能摧毁这个观察者?当我的异步数据从父组件加载时,我的子组件中只需要一次.
export default {
...
watch: {
data: function(){
this.sortBy();
},
},
...
}
Run Code Online (Sandbox Code Playgroud)
格雷戈尔;)
如果通过调用vm.$ watch函数动态构造一个观察程序,它将返回一个函数,该函数可以在稍后的某个时间点调用以禁用(删除)该特定观察程序.
不要像在代码中那样静态地将观察者放在组件中,而是执行以下操作:
created() {
var unwatch = this.$watch(....)
// now the watcher is watching and you can disable it
// by calling unwatch() somewhere else;
// you can store the unwatch function to a variable in the data
// or whatever suits you best
}
Run Code Online (Sandbox Code Playgroud)
可以从这里找到更详尽的解释:https://codingexplained.com/coding/front-end/vue-js/adding-removing-watchers-dynamically
这是一个例子:
<script>
export default {
data() {
return {
employee: {
teams: []
},
employeeTeamsWatcher: null,
};
},
created() {
this.employeeTeamsWatcher = this.$watch('employee.teams', (newVal, oldVal) => {
this.setActiveTeamTabName();
});
},
methods: {
setActiveTeamTabName() {
if (this.employee.teams.length) {
// once you got your desired condition satisfied then unwatch by calling:
this.employeeTeamsWatcher();
}
},
},
};
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5566 次 |
| 最近记录: |