请老师检查 我感觉我这样做还是很麻烦的,有没有更简便的方法呢?

请老师检查 我感觉我这样做还是很麻烦的,有没有更简便的方法呢?

<!DOCTYPE html>

<html>

<head>

    <title>vue组件化</title>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <style>

    button {

        padding: 10px 20px;

        margin: 20px auto;

        border-radius: 5px;

        outline: none;

    }

    .red {

        background: pink;

    }

    .green {

        background: green;

    }

</style>

</head>

<body>

<div id="app">

        <one></one>

        <two></two>

    </div>

    <script type="text/javascript">

        Vue.prototype.common=new Vue();

        Vue.component("one",{

           template:"<div><three></three></div>"

        });

        Vue.component("two",{

           template:"<button :class='bgColor' @click='clickMe'>组件2</button>", 

           data:function(){

             return {bgColor:"green"}

           },

           mounted:function(){

             this.common.$on("bgColorChangeTwo",arg=>{

                 this.bgColor=arg;

             })

           },

           methods:{

            clickMe:function(){


                this.common.$emit("bgColorChangeThree","green");

            }

           }         

        });

        Vue.component("three",{

           template:"<button :class='bgColor' @click='clickMe'>组件3</button>",

           data:function(){

             return {bgColor:""}

           },

           mounted:function(){

             this.common.$on("bgColorChangeThree",arg=>{

                 this.bgColor=arg;

             })

           },

           methods:{

            clickMe:function(){

                this.common.$emit("bgColorChangeTwo","red");

            }

           }   

        });

        var vm=new Vue({

            el:"#app"

        })

    </script>

</body>

</html>


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
好帮手慕糖 2020-06-05 11:27:48

同学你好,老师看了一下并没有很麻烦哦,这个题的思路其实就是稍微有些繁琐。代码实现正确,继续加油,祝学习愉快~

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师