Vue组件之间数据共享浅析

2022-11-23 15:09:35

目录组件数据共享父组件向子组件共享数据子组件向父组件共享数据兄弟组件共享数据组件数据共享组件之间的关系:在项目开发中,组件之间的最常用的关系分为两种:父子关系和兄弟关系。父组件向子组件共享数据通过自定...

目录
组件数据共享
父组件向子组件共享数据
子组件向父组件共享数据
兄弟组件共享数据

http://www.cppcns.com件数据共享

组件之间的关系:在项目开发中,组件之间的最常用的关系分为两种:父子关系和兄弟关系。

父组件向子组件共享数据

通过自定义属性实现父向子传值。

Vue组件之间数据共享浅析

Vue组件之间数据共享浅析

子组件向父组件共享数据

通过自定义事件实现子向父传值

Vue组件之间数据共享浅析

Vue组件之间数据共享浅析

兄弟组件共享数据

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

EventBus的使用步骤:

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

import Vue from 'vue'
// 向外共享 Vue 的实例对象
export default new Vue()

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

<template>
    <div class="left-container">
        <h3>Left组件--{{count}}</h3>
        <button @click="send">点击给Right发送数据</button>
    </div>
</template>
<script>
    // 1.导入 eventBus.js 模块
    import bus from './eventBus' 
    export default{
        data(){
            return {
                // 兄弟组件要传送的数据
                str:'我想对你说:hello world'
            }
        },
        methods:{
            send(){
                // 2.通过eventBus来发送数据
                bus.$emit('share',this.str)
            }
        }
    }
</script>
<style lang="less" scoped>
    h3{
        color: #f00;
    }
    .left-container{
        padding: 0 20px 20px;
        background-color: orange;
        min-height: 250px;
        Flex: 1;
    }
    ::v-deep h5{
        color:#00f
    }
</style>

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

<template>
    <div class="right-container">
        <h3>Right组件</h3>
        {{msgFromLeft}}
    </div>
</template>
<script>
    // 1.导入 eventBus.js 模块
    import bus from './eventBus'
    export default{
        data(){
            return {
                // 兄弟组件要接受的数据
                msgFromLeft:""
            }
        },
        created(){
            bus.$on('share',val=>{
                this.msgFromLeft = val
                // console.log('在Right组件中定义的share被触发了!',val);
            })
        }
    }
</script>
<style>
    .right-container{
        padding: 0 20px 20px;
        background-color: orange;
        min-height: 250px;
        flex: 1;
    }
</style>

Vue组件之间数据共享浅析

到此这篇关于Vue组件之间数据共享浅析的文章就介绍到这了,更多相关Vue组件数据共享内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!