watch

作者: hszz | 来源:发表于2021-11-08 16:31 被阅读0次

    • handler 触发的处理函数
    • immediate 初始值监听
    • deep 深度监听,不推荐使用,建议直接监听 对象对应属性值,如例子中的country.city.
    <script>
        export default {    
            data() {
                return {
                    color: 'red',
    
                    country: {
                        city: 'hszz',
                    }
                }
            },
            
            watch: {
                color: { // 监听color
                    handler(newVal, oldVal) { // 监听触发的处理函数
                        console.log('oldVal:' + oldVal)
                        console.log('newVal:' + newVal)
                    },
                    immediate: true, // 开启初始值监听(就初始值就会触发handler), 否则只有监听值改变才会触发handler
                },
                
                // country: {
                //  handler(newVal, oldVal) {
                //      console.log('oldVal:' + oldVal)
                //      console.log('newVal:' + newVal)
                //  },
                //  deep: true, // 开启深度监听。
                //  // 未开启时对象-属性值变化不会触发handler
                //  // 但是不推荐使用
                //  // 推荐直接监听 对象对应属性值,如下列子
                // },
    
                'country.city': { // 监听country对象的city属性
                    handler(newVal, oldVal) {
                        console.log('oldVal:' + oldVal)
                        console.log('newVal:' + newVal)
                    },
                    immediate: true,        
                },
            }
        }
    </script>
    
    <template>
        <div class="">
            color->:{{color}}
        </div>
        <div class="">
            country.city->:{{country.city}}
        </div>
            <button type="button" @click="color += 'hszz'">修改color触发监听</button>
            <button type="button" @click="country.city += 'hszz'">修改city触发监听</button>
        </div>
    </template>
    

    相关文章

      网友评论

          本文标题:watch

          本文链接:https://www.haomeiwen.com/subject/foguzltx.html