Vue中组件之间数据通信

组件数据传递

组件数据传递的实现方式

  1. vuex
  2. prop和emit方式
  3. store
  4. eventBus

1.父传子

父组件向组件传递数据,通过子组件中prop属性接受父作用域中的属性
父组件

<part-component buttonKey="列斯"></part-component>

export default {
  name: 'modulePart1',
  components: { partComponent },
  data () {
  }
}

子组件

export default {
  name: 'partComponent',
  props: {
    buttonKey: {
      type: String
    }
  },
  data () {
    return {
    }
  }
}

注意

  • 传递数组、布尔、对象、数字必须使用动态prop的方式,如:prop="number"
  • 传递一个对象的所有property使用:prop="post",post为对象
  • 子组件使用inheritAttrs:false,避免未在prop中注册的属性

子传父使用emit事件传递的方式
父组件

<part-component buttonKey="列斯" @fnToFather="fnToFather"></part-component>

fnToFather (s) {
      this.info = s
    }

子组件

<ta-button @click="fnToFather">{{buttonKey}}</ta-button>

fnToFather () {
  this.$emit('fnToFather', '来自子组件的数据')
}

2.兄弟

  • 通过子传父,父再传子的方式,这里不介绍
  • 通过eventBus实现
  1. 声明Bus总线
//声明Bus.js
import Vue from 'Vue'
export default new Vue

2.发出事件

import Bus from 'Bus.js'
Bus.$emit("eventName","content")

3.监听事件

import Bus from 'Bus.js'
Bus.$on("eventName",data=>{
    //数据处理
})
  • 通过sessionstorage实现
  1. A组件
sessionStorage.setItem();
  1. B组件
sessionStorage.getItem()

3.爷孙

  • 通过爷传父,父传子事件
  • 通过eventBus总线实现
  • sessionstorge实现
原文地址:https://www.cnblogs.com/cxyc/p/13614780.html