vue父子组件通信

父组件传递数据给子组件

父组件

<parent>
  <child :child-msg="msg"></child> //这里必须要用 - 代替驼峰
</parent>

data(){
  return {
    msg: [1,2,3]
  };
}

子组件

Vue.component('child', {
  // 声明 props
  props: ['childMsg'],
  // 就像 data 一样,prop 也可以在模板中使用
  // 同样也可以在 vm 实例中通过 this.childMsg 来使用
  template: '<span>{{ childMsg }}</span>'
})

子组件传递数据给父组件

子组件

<template>
    <div @click="tellParent"></div>
</template>
methods: {
    tellParent() {
        this.$emit('toParent', 'Hi, father!'); // 主动触发toParent方法,'Hi, father!'为向父组件传递的数据
    }
}

父组件

<parent>
    <child @toParent="change" :msg="msg"></child> // 监听子组件触发的toParent事件, 然后调用change方法
</parent>
methods: {
    change(msg) {
        this.msg = msg;
    }
}

父子组件数据双向绑定

父组件

<text-document v-bind:title.sync="doc.title"></text-document>

 子组件

this.$emit('update:title', newValue)
原文地址:https://www.cnblogs.com/zhoulixue/p/9518569.html