Vue组件之间的通信

项目中写组件一般是在component文件夹下,注册过的组件想要全局使用则需要在main.js中引入,局部使用的话就在需要的地方引入。我是全局引入:

(一)父组件向子组件传值(子组件通过props接收父组件的值)

父组件代码:app.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view/>
    <son :message="msg"></son>
  </div>
</template>

<script>
export default {
  name: 'App',
  data(){
      return {
        msg: "我是父组件的数据"
      }
  }
}
</script>

子组件代码:SonComponent.vue

<template>
  <section>
    <h1>{{title}}</h1>
    <div>{{message}}</div>
  </section>
</template>
<script>
export default {
  name: 'SonComponent',
  data () {
    return {
      title: '子组件页面'
    }
  },
  props:['message']
}
</script>

效果如下:

 

(二)子组件→父组件通信(子组件通过$emit( eventName)来触发一个事件)

 父组件代码:app.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view/>
    <son-btn @connect="say"></son-btn>
  </div>
</template>

<script>
export default {
  name: 'App',
  data(){
      return {
        msg: "我是父组件的数据"
      }
  },
  methods:{
    say(arg){
      console.log(`大家好,我监听到了事件connect的触发,并且接收到了参数${arg[0]}`);
    }
  }
}
</script>

子组件代码:SonComponent.vue

<template>
  <section>
    <h1>{{title}}</h1>
    <button @click="send">按钮</button>
  </section>
</template>
<script>
  export default {
    name: 'Son1Component',
    data () {
      return {
        title: '子按钮'
      }
    },
    methods:{
        send(){
          this.$emit('connect',[1,2,3]);
        }
    }
  }
</script>

效果如下: 

 (三)非父子组件的通信

除了父子组件的相互通信,非父子关系的组件该如何通信,我们可以巧妙地利用一个空的vue实例来作为一个中央事件总线。

但是在实际开发中,我们不会这么做,我们会使用专门用于状态管理的 vuex ,关于vuex后续更新。

原文地址:https://www.cnblogs.com/linjiu0505/p/10875770.html