Vue组件之间数据共享浅析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vue组件之间数据共享浅析

亦世凡华、   2022-11-24 我要评论

组件数据共享

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

父组件向子组件共享数据

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

子组件向父组件共享数据

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

兄弟组件共享数据

在 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>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们