麻烦老师,页面显示不出来,并且是对着模板写的,老师能说一下思路吗,自己写没有思绪

来源:4-10 编程练习

superman888

2020-09-14 20:07:11

<!DOCTYPE html>

<html lang="en">

  <head>

    <meta charset="UTF-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title></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">

      <!-- 在此补充代码 -->

      <child-one></child-one>

      <child-two></child-two>

    </div>

    <script>

      Vue.prototype.bus = new Vue();


      Vue.component("childOne", {

        props: {},

        template: "<div>组件1<childThree></childThree></div>",

        methods: {},

      });

      Vue.component("childTwo", {

        data: function () {

          return {

            className: "green",

            green: "green",

          };

        },

        template:

          '<button @click="handClickTwo" :class="className">组件2</button>',

        methods: {

          handClickTwo: function () {

            this.bus.$emit("changeComonpentThree", this.green);

          },

        },

        mounted: function () {

          var this_ = this;

          this.bus.$on("changeComonpentTwo", function (msg) {

            this_.className = msg;

          });

        },

      });


      Vue.component("childThree", {

        data: function () {

          return {

            className: "",

            pink: "pink",

          };

        },

        template:

          "<button @click='handClickThree' :class='className'>组件3</button>",

        methods: {

          handClickThree: function () {

            this.bus.$emit("changeComonpentTwo", this.pink);

          },

        },

        mounted: function () {

          var this_ = this;

          this.bus.$on("changeComonpentThree", function (msg) {

            this_.className = msg;

          });

        },

      });


      var vm = new Vue({

        el: "#app",

      });

    </script>

  </body>

</html>




写回答

1回答

好帮手慕久久

2020-09-15

同学你好,由于组件3中,变量pink的值写错了,所以没有效果。变量pink代表的类名应该是red,如下:

http://img.mukewang.com/climg/5f60241b09733dce06200211.jpg

所以要做如下修改:

http://img.mukewang.com/climg/5f60242309c543a109400277.jpg

整体的思路如下:

点击组件3,让组件2变色,那么就要给组件3绑定click事件,在click事件中,使用Bus触发一个自定义事件,并把参数传给组件2,而组件2需要监听这个自定义事件,在该事件中,改变自身的样式,过程如下:

http://img.mukewang.com/climg/5f602432097a68ff11890555.jpghttp://img.mukewang.com/climg/5f60243709642eef10800462.jpg

组件2的过程,和组件3一样。

如果我的回答帮到了你,欢迎采纳,祝学习愉快!

0

0 学习 · 10739 问题

查看课程