vue 子组件接收父组件的props,使用emit给父组件之后如何在传递给子组件

//父组件
<device-topo
    :superGw='superGw'
    :node-show='changeChildData'>
</device-topo>

changeChildData(type, action, index){
    this.superGw.expandDevChild   = !this.superGw.expandDevChild
    console.log(this.superGw.expandDevChild)//这里打印出来可以看到值已经修改
},
//子组件函数
handleChildSpotData(){
    console.log('子组件接收到的数据',this.superGw)
},

在父组件中可以看到值已经修改,但是在子组件中没有响应,请问应该怎么处理呢

阅读 4.2k
5 个回答

可以利用vue的修饰符 .sync 来实现,非常简单,使用方法如下:

<device-topo
    :superGw.sync='superGw'>
</device-topo>

当子组件需要更新 superGw 的值时,它需要显式地触发一个更新事件:

handleChildSpotData() {
   this.$emit('update:superGw', this.superGw)
}
新手上路,请多包涵

可以在子组件中用 watch 或 computed 对父组件传递的 propos 建立依赖关系,不知道这样是否能满足需求。

需要在子组件中使用watch监控父组件传递过来的数据的实时变化。根据传递过来的数据类型不同,watch方法略有差异。
1、传递过来的数据是基础类型

props: {
    argumentName : String   //基础类型,如number,string,bool
},
watch: {
    argumentName(newValue, oldValue) {
        console.log(newValue)
    }
}

2、传递过来的数据是数组类型

props: {
    argumentName : Array
},
watch: {
    argumentName:{
        handler(newValue, oldValue) {
      for (let i = 0; i < newValue.length; i++) {
        if (oldValue[i] != newValue[i]) {
          console.log(newValue)
        }
      }
    },
    deep: true
    }
}

3、传递过来的数据是object对象类型

props: {
    argumentName : Object
},
watch: {
    argumentName:{
        handler(newValue, oldValue) {
       console.log(newValue)
      },
    deep: true
    }
}
this.superGw.expandDevChild   = !this.superGw.expandDevChild

你这修改的是对象的属性,vue监听不到。使用this.$set()试试

修改对象建议使用set,深入响应式原理

this.$set(this.superGw, 'expandDevChild', !this.superGw.expandDevChild)

对于父组件变量的变更,子组件并不会因为某函数使用了该变量而执行,如果需要在变量修改后执行某函数需要自己写监听方法

watch: {
    superGw: {
        deep: true, // 可以对对象进行深度监听
        handler(){
            doSometing()
        }
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题