创建事件中 watch 属性与 $watch 方法的区别(Vue)
Difference in watch properties vs $watch method in created event (Vue)
在 Vue 中 watch 属性与 $watch 方法有什么区别吗?例如,我试图理解为什么作者在下面的代码中使用 $watch 事件而不是 watch 属性。
created () {
const routes = this.mainMenu.find(item => item.path === '/')
this.menus = (routes && routes.children) || []
// 处理侧栏收起状态
this.$watch('collapsed', () => {
this.$store.commit(SIDEBAR_TYPE, this.collapsed)
})
this.$watch('isMobile', () => {
this.$store.commit(TOGGLE_MOBILE_TYPE, this.isMobile)
})
},
如果说我如下移动$watch,有什么不同吗?
watch: {
isMobile : function(value) {
this.$store.commit(TOGGLE_MOBILE_TYPE, value)
},
collapsed : function(value) {
this.$store.commit(SIDEBAR_TYPE, value)
}
},
created () {
}
请指教
watch
选项在后台使用 this.$watch
方法,因此基本相同。
唯一的区别是 this.$watch
returns 您可以调用一个函数来停止观察者:
const queryWatcher = this.$watch('$route.query', doSomethingFunction)
...
queryWatcher() // Stop the watcher
使用 this.$watch
没有意义,因为您不需要停止功能,因此您可以安全地将它们移至 watch
选项 属性。
在 Vue 中 watch 属性与 $watch 方法有什么区别吗?例如,我试图理解为什么作者在下面的代码中使用 $watch 事件而不是 watch 属性。
created () {
const routes = this.mainMenu.find(item => item.path === '/')
this.menus = (routes && routes.children) || []
// 处理侧栏收起状态
this.$watch('collapsed', () => {
this.$store.commit(SIDEBAR_TYPE, this.collapsed)
})
this.$watch('isMobile', () => {
this.$store.commit(TOGGLE_MOBILE_TYPE, this.isMobile)
})
},
如果说我如下移动$watch,有什么不同吗?
watch: {
isMobile : function(value) {
this.$store.commit(TOGGLE_MOBILE_TYPE, value)
},
collapsed : function(value) {
this.$store.commit(SIDEBAR_TYPE, value)
}
},
created () {
}
请指教
watch
选项在后台使用 this.$watch
方法,因此基本相同。
唯一的区别是 this.$watch
returns 您可以调用一个函数来停止观察者:
const queryWatcher = this.$watch('$route.query', doSomethingFunction)
...
queryWatcher() // Stop the watcher
使用 this.$watch
没有意义,因为您不需要停止功能,因此您可以安全地将它们移至 watch
选项 属性。