子组件使用 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# 侦听器
来源: http://www.bubuko.com/infodetail-2966998.html