vue常用的两种组件通讯方式

54 阅读1分钟

父传子

父组件

<template>
  <div id="app">
  <cd :msg="sg"></cd> <!-- 使用子组件 -->
  </div>
</template>
<script>
import cd from './components/cd.vue';
export default {
  name: 'App',
  data(){
    return{
      // 默认选择的项
      sg:'我是父组件的msg'
    } },
  components: {
cd
   }
}
</script>

子组件(使用props接收)

  <div>{{ msg }}</div>
  <!-- 直接使用拿过来的msg -->
</template>

<script>
export default {
  data() {
    return {};
  },
  props: {
    msg: String,
  },
};
</script>

<style>
</style>

子传父

子组件写法

  1. 在子组件里面设置一个按钮绑定一个send事件
<button @click="send">发送</button>

2.使用this.$emit方法

send(){
this.$emit('send',this.children)

}}

第一个参数‘send’是父组件接受的触发方法,‘children’是要发送的数据

父组件写法

监听子组件事件send,然后调用sendchildren事件

{{ array }}
<cd :msg="sg" @send="sendchildren"></cd>

sendchildren事件

    sendchildren(qaq) {
      this.array = qaq;
    },

这样子就把子组件的数据拿到了父组件的array数组里面