問題
在項目中遇到一個問題,父組件向子組件傳值,子組件監聽傳入對象的某個屬性的時候,發現子組件使用deep watch都不能監聽到屬性的變化。今天終於在網上找到了答案,在這裏把方法記錄下來。參考網址https://blog.csdn.net/oLianyo...
解決
爲啥會出現這種問題?受ES5的限制,Vue.js不能檢測到對象屬性的添加或刪除。請參照https://v1-cn.vuejs.org/guide...
解決方法html
<template> <div> <p @click="fun1" style="color: blue">方式一</p> <p @click="fun2" style="color: blue">方式二</p> </div> </template> <script> export default { data () { return { p: {a: 1} } }, methods: { fun1 () { console.log('click 1111') // this.p.b = 2 // 經過點方法賦值,發現觀察不到p的變化 this.$set(this.p, 'b', 2) // 第一種解決方式,能夠查看日誌看到已經監聽到了變化 }, fun2 () { console.log('click 2222') this.p = Object.assign({}, this.p, {c: 3}) } }, watch: { p: { handler (cval, oval) { console.log('--------') console.log(cval, oval) }, deep: true } } } </script> <style> </style>
在個人項目中我引用了第一種方法。我以爲第一種方法更適合個人項目。vue