组件之间的数据共享

139 阅读1分钟
  • 父传子

使用自定义属性: 在子组件中通过props声明一些属性,父组件在使用子组件时,通过属性绑定的方式,传递

// 子组件 
<template>
    <div>
        <h1>Son 组件</h1>
        <p>父组件传递过来的 msg 值是: {{ msg }}</p>
        <p>父组件传递过来的 user 值是: {{ user }}</p>
    </div>
</template>
// 在子组件中通过props声明一些属性
props: ['msg', 'user']
// 父组件   (子组件有啥属性就给他传啥属性)
<Son :msg="message" :user="userInfo"></Son>

data() {
    return {
        message: 'hello vue.js',
        userInfo: { name: 'Tom', age: '18'}

    }
}
  • 子传父

子组件自定义一个事件,父组件去绑定

export default {
// 子组件 
    data() {
        return { count: 0}
    },

    methods: {
        add() {
            this.count += 1;
            // 这里修改数据时,通过this调用$emit()触发自定义事件
            this.$emit('numchange', this.count)//**在子组件中任意去定义方法的名字如numchange,但一旦名字固定下来了,在绑定事件监听的时候必须绑定这个名字
        }
    }
}
// 第1个是触发的自定义事件名字
// 第2个参数是发给父组件的数据
// 父组件
// <Son @numChange="getNewCount"></Son> //绑定哪个自定义事件就在前面加@(当$emit触发numchange事件,那么也就触发这个事件绑定的处理函数getNewCount)
export default {
    data() {
        return { coutFromSon: 0 }
    },
    methods: {
        getNewCount(val) {
            this.countFromSon =val;
        }
    }
}
</script>
  • 兄弟之间

eventBus

  1. $emit发布事件,兄弟组件A(数据发送方)
  2. 调用$on 绑定事件,兄弟组件B(数据接收方)
// 发送方 组件A
import bus from './eventBus.js'//eventBus创建后
export default {
    data() {
        return {
            msg: 'hello vue.js'
        }
    },
    // eventBus创建后
    methods: {
        sendMsg() {
            bus.$emit('share', this.msg)//参数1:事件 参数2:传递的数据
        }
    }
}
// 接收方 组件B
import bus from './eventBus.js'    //eventBus创建后引入
// 再定义一个上面一样的 来接收数据 
export default {
    data() {
        return {
            msgFromTop: ''//接收到数据之后存到msgFroTop中
        }
    },
    created() {
        bus.$on('share', val => {
            this.msgFromTop = val
        })//通过$emit发送的数据 就通过形参val接收到了
    }
}

// 创建eventBus 对象
import Vue from 'vue'
// 创建对象之后 要将这个实例共享出去
export default new Vue()