Vue组件间传值(bus)

css样式

button {
        padding: 10px 20px;
        margin: 20px auto;
        border-radius: 5px;
        outline: none;
    }

    .red {
        background: pink;
    }

    .green {
        background: green;
    }

js

Vue.prototype.bus = new Vue();
        // 组件一
        Vue.component("compone", {
            template: "<div><compthree></compthree></div>"
        })
        // 组件二
        Vue.component("comptwo", {
            data: function () {
                return {
                    green: "green",
                    className: ""
                }
            },
            template: "<button @click='change' :class='className'>组件二</button>",
            methods: {
                change: function () {
                    this.bus.$emit("changeGreen", this.green);
                }
            },
            mounted: function () {
                var _this = this;
                this.bus.$on("changeRed", function (value) {
                    _this.className = value;
                })
            }
        })
        // 组件三
        Vue.component("compthree", {
            data: function () {
                return {
                    red: "red",
                    className: ""
                }
            },
            template: "<button @click='change' :class='className'>组件三</button>",
            methods: {
                change: function () {
                    this.bus.$emit("changeRed", this.red);
                }
            },
            mounted: function (){
                var _this = this;
                this.bus.$on("changeGreen", function (value) {
                    _this.className = value;
                })
            }
        })
        var vm = new Vue({
            el: "#app"
        })

菜鸟的笔记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值