发布时间:
watch 监听组件 prop 参数变化 #
newVal
:新的新值oldVal
:旧的数据
基础版本 #
组件创建时,不会触发 watch
中的监听函数,下次 props
参数变化会触发 watch
中函数。
export default {
name: "message",
props: {
user: { // 用户 id
type: String
},
apiKey: { // API Key
type: String
},
},
watch: {
apiKey(newVal, oldVal) {
console.log('apiKey newVal', newVal, "apiKey oldVal:", oldVal);
},
user(newVal, oldVal) {
console.log('usern ewVal', newVal, "user oldVal:", oldVal);
}
}
}
进阶版 #
马上会调用 watch
中的函数
immediate
:true 立即执行handler
:该回调将会在侦听开始之后被立即调用
export default {
name: "message",
props: {
user: { // 用户 id
type: String
},
apiKey: { // API Key
type: String
},
},
apiKey: {
handler(newVal, oldVal) {
console.log('apiKey newVal', newVal, "apiKey oldVal:", oldVal);
},
immediate: true
},
user: {
handler(newVal, oldVal) {
console.log('user newVal', newVal, "user oldVal:", oldVal);
},
immediate: true
}
}
高级版 #
马上会调用 watch
中的函数
deep
:true 深度监听handler
:该回调会在任何被侦听的对象的 property 改变时被调用,不论其被嵌套多深
export default {
name: "message",
props: {
user: { // 用户 id
type: String
},
apiKey: { // API Key
type: String
},
},
apiKey: {
handler(newVal, oldVal) {
console.log('usernewVal', newVal, "useroldVal:", oldVal);
},
deep: true
},
user: {
handler(newVal, oldVal) {
console.log('usernewVal', newVal, "useroldVal:", oldVal);
},
deep: true
}
}
警告
注意,不应该使用箭头函数来定义 watcher
函数 (例如 searchQuery: newValue => this.updateAutocomplete(newValue)
)。
理由是箭头函数绑定了父级作用域的上下文,所以 this
将不会按照期望指向 Vue 实例,this.updateAutocomplete
将是 undefined。