初识vue 2.0(13):子组件使用watch监听父组件变化

子组件使用created或者mounted通常只能在组件初始化的时候,获取父组件传过来的props数据。

父组件props数据发生变化,子组件默认无法感知,因此需要手动实现子组件监听父组件变化的功能。

一般的值类型数据,可以直接使用watch监听:

watch: {
    msg(newVal, oldVal){//对引用类型的值无效
        console.info('value changed ', newVal)
    }
}

引用类型,普通watch方法,无法监听到引用类型内部的变化。

解决此问题,可以在父组件中将变化的对象变成一个新的对象,自主实现深拷贝,例如:

methods: {
    addAge(){
        this.child.age ++;
        this.child = JSON.parse(JSON.stringify(this.child));
    }
}

但是这样做不是很优雅,vue提供了方便的深拷贝的方式去监听引用类型值的变化,例如:

watch: {
    msg: {
        handler(newVal, oldVal) {
            console.info('value changed 2', newVal)
        },
        deep: true
    }
}

完整例子:

1. 父组件Game.vue向子组件传递props值

<template>
    <div class="game">
        <button @click="addAge">birthday++</button>
        <DNF :msg="child"></DNF>
    </div>
</template>
<script>
import DNF from './DNF'
export default {
    name: 'Game',
    components: {
        DNF
    },
    data () {
        return {
            child:{name:'dnf',age:18},
        }
    },
    methods: {
        addAge(){
            this.child.age ++;
            //this.child = JSON.parse(JSON.stringify(this.child));
        }
    }
}
</script>

2. 子组件DNF.vue 使用watch监听父组件中msg的变化,因为msg是一个object,因此设置 deep:true。

<template>
    <div class="dnf"></div>
</template>
<script>
export default {
    name: 'DNF',
    props: ["msg"],
    watch: {
        msg(newVal, oldVal){//对引用类型的值无效
            console.info('value changed 1', newVal)
        },
        msg: {
            handler(newVal, oldVal) {
                console.info('value changed 2', newVal)
            },
            deep: true
        }
    },
}
</script>

官方文档:https://cn.vuejs.org/v2/guide/computed.html#侦听器

猜你喜欢

转载自www.cnblogs.com/phptree/p/10428726.html