组件之间的数据共享

发布时间 2023-03-28 10:04:17作者: Dinesaw

组件之间的数据共享:

一、父组件传递给子组件

①App.vue

template

给子组件绑定值

<Left :msg="message" :user="userinfo"></Left>

script

声明需要发送的数据

data() {
    return{
      message: "hello,这是来自父组件的祝福:祝你开心",
      userinfo: { name: 'wsc', age: 18 }
    }  
  }

②Left.vue

script

声明props

props: ['msg', 'user'],

template

直接使用

    <p>msg 的值是:{{ msg }}</p>
    <p>user 的姓名是:{{ user.name }}</p>
    <p>user 的年龄是:{{ user.age }}</p>

二、子组件传递给父组件

①Right.vue

template

设定一个增加按钮

<button @click="add">Add1</button>

script

设定add() 的方法和数据

data() {
      return{
        count:0
      }  
    },
methods: {
        add() {
            this.count+=1
            this.$emit('numchange',this.count)
        }
    }

②App.vue

template

Right组件,一产生就触发getNewCount这个事件

<p>countFromRight:{{ countFromRight }}</p>
<Right @numchange="getNewCount"></Right>

script

设定add() 的方法和数据

data() {
    return{
      countFromRight:0
    }  
  },
  components: {
    Right
  },
  methods: {
    getNewCount(val){
      this.countFromRight = val
    }
  }

三、兄弟组件相互传递

创建@/components/eventBus.js

import Vue from 'vue'
export default new Vue()

①在Right.vue和Right.vue中都导入eventBus.js 模块

import bus from './eventBus.js'

②Left.vue

template

    <h3>这个是Left</h3>
    <button @click="send">把好诗发给 Right</button>

script

    data() {
    return {
      str: `左组件写的诗:黑云压城城欲摧,渚青沙白鸟飞回。借问酒家何处是,半江瑟瑟半江红!`,
      arr: [
        { id: 1, name: 'zs' },
        { id: 2, name: 'ls' }
      ]
    }
  },
    methods: {
    send() {
      // 2. 通过 eventBus 来发送数据,发送方:
      bus.$emit('share', this.str)
    }
  }

③Right.vue

template

        <h3>这个是right</h3>
        <p>{{ msgFromLeft }}</p>

script

 data() {
      return{
        msgFromLeft: ''
      }  
    },
    created() {
    // 2. 为 bus 绑定自定义事件,接收方:
    bus.$on('share', val => {
      console.log('在 Right 组件中定义的 share 被触发了!', val)
      this.msgFromLeft = val
    })
  }