10-组件之间的数据共享

119 阅读1分钟

父组件向子组件共享数据

父组件向子组件共享数据需要使用自定义属性。示例代码如下:

chrome_PXQUxjaPWX

子组件向父组件共享数据

子组件向父组件共享数据使用自定义事件。示例代码如下:

chrome_rrQ1N4HMZ2

兄弟组件之间的数据共享

vue2.x 中,兄弟组件之间数据共享的方案是 EventBus。

chrome_uOqoiqkG6O

EventBus 的使用步骤:

① 创建 eventBus.js 模块,并向外共享一个 Vue 的实例对象

② 在数据发送方,调用 bus.$emit('事件名称', 要发送的数据) 方法触发自定义事件

③ 在数据接收方,调用 bus.$on('事件名称', 事件处理函数) 方法注册一个自定义事件

案例

父组件 App.vue

<template>
  <div class="app-container">
    <h1>App 根组件 --- {{ FromSon }}</h1>
    <hr />
    <div class="box">
      <Left :msg="message" :user="userinfo"></Left>
      <Right @numchange="getNewCount"></Right>
    </div>
  </div>

</template>

<script>
import Left from '@/components/Left.vue'
import Right from '@/components/Right.vue'

export default {
  data(){
    return {
      message:'Hello Vue',
      userinfo:{name:'zs',age:18},
      // 定义 FromSon 来接收子组件传递过来的数据
      FromSon:0
    }
  },
  components:{
    Left,
    Right
  },
  methods:{
    // 获取子组件传递过来的数据
    getNewCount(val){
      console.log('被触发了',val)
      this.FromSon = val

    }
  }
}
</script>

<style lang="less">
.app-container {
  padding: 1px 20px 20px;
  background-color: #efefef;
}
.box {
  display: flex;
}
</style>

子组件 Left.vue

<template>
  <div class="left-container">
    <h3>Left 组件</h3>
    <p>{{ msg }}</p>
    <p>{{ user }}</p>
    <button @click="send">发送给Right</button>
  </div>
</template>

<script>
// 导入eventBus.js
import bus from './eventBus.js'
export default {
  props:['msg','user'],
  data(){
    return {
      str:'这是发送的内容'
    }
  },
  methods:{
    send(){
      bus.$emit('share',this.str)
    }
  }
}
</script>

<style lang="less">
.left-container {
  padding: 0 20px 20px;
  background-color: orange;
  min-height: 250px;
  flex: 1;
}
</style>

子组件 Right.vue

<template>
  <div class="right-container">
    <h3>Right 组件 --- {{ count }}</h3>
    <button @click="add">+</button>
    <p>{{ mesgFromLeft }}</p>
  </div>
</template>

<script>
// 导入 
import bus from './eventBus.js'
export default {
  data(){
    return {
      count:0,
      mesgFromLeft:''
    }
  },
  methods:{
    add(){
      this.count ++
      // 把自增结果 传给父组件
      this.$emit('numchange',this.count)
    }
  },
  created(){
    bus.$on('share',(val) => {
      console.log('被触发了',val);
      this.mesgFromLeft = val
    })
  }
}
</script>

<style lang="less">
.right-container {
  padding: 0 20px 20px;
  background-color: lightskyblue;
  min-height: 250px;
  flex: 1;
}
</style>

chrome_6xZTfNMQeE.png