关于前端:vue-20-组件传值-3

5次阅读

共计 967 个字符,预计需要花费 3 分钟才能阅读完成。

形容

非父子组件传值

1、新建一个 jsx 文件   而后引入 vue  实例化 vue  最初裸露这个实例
2、在要播送的中央引入方才定义的实例
3、通过 VueEmit.$emit('名称','数据')
4、在接管收数据的中央通过 $om 接管播送的数据
    VueEmit.$on('名称',function(){办法})

新建 jsx 文件 VueEvent

import Vue from 'vue';
consot VueEvent = new Vue()
export default VueEvent;

父组件

<template>
    <div id="father">
         首页组件
        <button @click="emitNews()"> 给 News 组件播送数据 </button>
    </div>
</template>

<script>
    import SliderHeader from './SliderHeader.vue';// 引入子组件
    export default{data() {
            return { // 父组件的值
               msg: '我是一个 father 组件',
               title: '首页'
            }
        },
        methods: {emitNews(){
                // 播送数据
                VueEvent.$emit('to-news',this.msg)
            }
        },
        mounted() {
            // 监听 news 播送的数据
            VueEvent.$on('to-home',function(data){console.log(data);
            })
        }
    }
</script>

<style lang="scss" scoped>
    /*css scoped 设置 部分作用域  */
    h2{color:red} 
</style>

子组件 Header

<template>
    <div>
        <h2> 我是头部组件 --{{msg}}</h2>
        <button @click="emitHome()"> 给 Home 组件播送数据 </button>
    </div>
</template>

<script>    
export default {data() {
        return {msg: '子组件的 msg'}
    },
    methods: {emitHome() { 
                // 播送
                VueEvent.$emit('to-home', this.msg)
            },
            mounted() {VueEvent.$on('to-news',function(data){console.log(data);
            })
        }
    }
}
</script>
正文完
 0