Vue组件间通信

Vue中组件的通信方式大致有:父——子、子——父、兄弟之间的通信

父子传值

父——子

父组件向子组件传值的时候,使用v-bind绑定属性,携带要发送的数据,子组件通过props接收这个数据(要跟属性名相同)

Father.vue

<template>
  <div class="father">
    <h2>Father</h2>
    <Son :fromFather="fromFatherM" />
  </div>
</template>
<script>
import Son from "@/components/Son";
export default {
  components: {
    Son,
  },
  data() {
    return {
      fromFatherM: "父组件的消息",
    };
  },
};
</script>

为了容易区分属性名和数据,数据后加了个M,子组件接收数据时要使用这里面的属性名

Son.vue

<template>
  <div id="son">
    <h2>Son</h2>
    接收:{{fromFather}}
  </div>
</template>
<script>
export default {
  props: {
    fromFather: String,		// 接收参数并指定类型
  },
  data() {
    return {};
  },
};
</script>

效果如图

image-20200804205932103

子——父

子组件向父组件发送数据要通过方法来完成,父组件引用子组件的时候向子组件传递一个方法,子组件通过触发事件向方法中传参来向父组件发行数据

Father.vue

<template>
  <div class="father">
    <h2>Father</h2>
    接收:{{sonData}}
    <Son :fromFather="fromFather" @receive="receiveData" />
  </div>
</template>
<script>
import Son from "@/components/Son";
export default {
  components: {
    Son,
  },
  data() {
    return {
      fromFather: "父组件的消息",
      sonData: "",
    };
  },
  methods: {
    receiveData(d) {	// 接收数据并赋值
      this.sonData = d;
    },
  },
};
</script>

使用@receive绑定事件,子组件发出数据时需要向这个绑定事件提交

Son.vue

<template>
  <div id="son">
    <h2>Son</h2>
    接收:{{fromFather}}
    <input type="text" v-model="fromSon" />
    <button @click="sonHandle">send</button>
  </div>
</template>
<script>
export default {
  props: {
    fromFather: String,
  },
  data() {
    return {
      fromSon: "",
    };
  },
  methods: {
    sonHandle() {
      this.$emit("receive", this.fromSon);	// 发送数据的事件
    },
  },
};
</script>

效果如图

![QQ录屏20200804211211 00_00_00-00_00_30](https://cdn.easyremember.cn/img/QQ录屏20200804211211 00_00_00-00_00_30.gif)

使用$parent和$children

官方文档中还给出了一对API

image-20200804212823114

mounted() {
console.log(this.$parent.id + "$parent");
},

image-20200804212833571

mounted() {
  console.log(this.$children[0].id + "$children");
},

这里一定要注意获取的数组

还可以通过$refs来获取,如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件实例

image-20200804213444179

image-20200804213414669

可以获取

上面三种方式的结果如图

image-20200804214201265

兄弟组件

兄弟组件传值可以借助一个空白组件,如果项目较大,可以使用Vue官方状态管理Vuex,之后会发Vuex的介绍


前端小白