vue中父子通信是常用到的技术点,有多种方法可以进行传值,复杂的传值方式去参考vueX。今天我们简单说下常用的2种方式:

父传子:props传值
子传父:$emit

1. ----------父传子----------

父组件给子组件传值,需要在子组件中添加props进行接收父组件传来的值

父组件:
随便封装一个子组件,起名叫childComponent。给引入的子组件中传一个“我是父组件”,随便定义一个hello接收。

<!-- 父组件--><template>  <div class="aaa">      <childComponent hello="我是父组件"></childComponent>      </div></template>< >// 引入子组件import childComponent from "/components/childComponent.vue";export default {  data() {    return {};  },  components: {    // 要在components中注册子组件才能使用    childComponent  },  methods: {}};</ ><style scoped></style>

子组件:
div中的hello会显示“我是父组件”,这是从父组件通过props传过来的

<!-- 子组件--><template>  <div class="aaa">        <div>{{ hello }}</div>      </div></template>< >export default {  data() {    return {      // 因为props中接收了hello属性,所以data中不能再定义相同的hello属性。    };  },  // props 中接收在父组件中定义的hello  props: {    hello: {      type: String // 在hello中加入了type:String,是告诉其他人,hello只接收字符串内容,传其他的会报错。这样对于团队合作更严谨。当然可以什么都不加,直接写hello。    }  }};</ ><style scoped></style>

这样子组件在页面上就会显示“我是父组件”这句话了,当然,这个值可以动态绑定,传递你想要传递的值,也可以传递布尔值,数组等信息。

2.----------子传父 $emit----------

this.$emit(‘要触发的方法’,参数)

我们随便定义一个要触发的方法,叫 aaa,然后传一个 123 的参数给父组件

<!-- 子组件--><template>  <div class="aaa">    <button @click="handleClick">子组件</button>  </div></template>< >export default {  data() {    return {};  },  methods: {    // 点击按钮上边button按钮,调用这个handleClick方法,通过$emit触发aaa,把 123 传过去。父组件通过 aaa 接收这个值。(往下看父组件中的内容)。    handleClick() {      this.$emit("aaa", 123);    }  }};</ ><style scoped></style>

父组件:

父组件中引入的子组件里,放入刚才通过$emit触发的方法 aaa,然后随便定义一个方法 getChildData ,它的值就是传递过来的123

<!-- 父组件--><template>  <div class="aaa">    <childComponent @aaa="getChildData"></childComponent>  </div></template>< >// 引入子组件import childComponent from "/components/childComponent.vue";export default {  data() {    return {};  },  components: {    // 要在components中注册子组件才能使用    childComponent  },  methods: {    // aaa 接收到的属性,随便定义一个函数 getChildData 方法来接收    getChildData(data) {      console.log(data); // 这个data就是子组件传递过来的值 123    }  }};</ ><style scoped></style>

仔细看代码,相信你会理解的父子通信的。那么兄弟组件之间也可以通信,是通过子传父,在父传子,这样就实现了子和子传递了,也就是兄弟通信,父组件作为中间的桥梁。除了这种方法,还可以用中央事件总线(bus)来进行传递,不过现在很少会用到bus来实现传递了。

收藏 打印