vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > 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组件数据共享内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文