vue2.0 组件之间的通信

开始之前请先自行按照vue官方文档搭建项目

# 全局安装 vue-cli
$ npm install --global vue-cli
# 创建一个基于 webpack 模板的新项目
$ vue init webpack my-project
# 安装依赖,走你
$ cd my-project
$ npm install
$ npm run dev 

好了,这个时候就已经有了一个全新的vue项目


其实用到子组件和父组件之间传值的同学,应该都有一部分vue的使用经验了

那我们就直接上代码吧!


父组件 子组件

子组件child.vue
<template>
    <div>
        <p>{{ msg }}</p>
    </div>
</template>
<script>
    export default{
        props:["msg"]
    }
</script>
父组件parent.vue
<template>
    <div>
        <child-page v-bind:msg="statu">

        </child-page>
    </div>
</template>
<script>
    import ChildPage from "./child"
    export default{
        data(){
            return {
                statu:"hello word!"
            }
        }
        components:{
            ChildPage
        }
    }
</script>

这个时候就可以来一波测试了

来一波总结:

  • 子组件在props中创建一个属性,用以接收父组件传过来的值
  • 父组件中注册子组件
  • 在子组件标签中添加子组件props中创建的属性
  • 把需要传给子组件的值赋给该属性

子组件 → 父组件

子组件child.vue
<template>
    <div>
        <p>{{ msg }}</p>
        <button v-on:click=""></button>
    </div>
</template>
<script>
    export default{
        props:["msg"],
        methods:{
            childMsg(){
                this.$emit("getChildMsg","vue is very good!")
            }
        }
    }
</script>
父组件parent.vue
<template>
    <div>
        <child-page v-bind:msg="statu" v-on:getChildMsg="showChild">

        </child-page>
    </div>
</template>
<script>
    import ChildPage from "./child"
    export default{
        data(){
            return {
                statu:"hello word!"
            }
        },
        methods:{
            showChildMsg(data){
                console.log(data);
            }
        }
        components:{
            ChildPage
        }
    }
</script>

惯例,测试,总结。

  • 子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件
  • 将需要传的值作为$emit的第二个参数,该值将作为实参传给响应自定义事件的方法
  • 在父组件中注册子组件并在子组件标签上绑定对自定义事件的监听

同级 →同级
1. 我们先来创建中央事件总线,在src/assets/下创建一个eventBus.js,内容如下
(eventBus中我们只创建了一个新的Vue实例,以后它就承担起了组件之间通信的桥梁了,也就是中央事件总线。)

eventBus.js
import Vue from 'Vue'

export default new Vue;

第一个组件

first.vue
<script>
import bus from '../../assets/eventBus'
export default {
    methods:{
        //点击触发事件
        sendmsg(){
            bus.$emit('getId','hello word!');
        }
    }
}
</script>

第二个组件

second.vue
<script>
import bus from '../../assets/eventBus'
export default {
    mounted(){
        var self = this;
        bus.$on('getId',function(data){
            console.log(data);
        })
    }
}
</script>

注意:在组件里一定不要忘记引入eventBus.js,一个发射,一个接受

在通信中,无论是子组件向父组件传值还是父组件向子组件传值,他们都有一个共同点就是有中间介质,子向父的介质是自定义事件,父向子的介质是props中的属性。抓准这两点对于父子通信就好理解了。

差不多了吧,感觉我这个有问题或者你有问题的,欢迎留言!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值