Vue学习案例:自定义事件练习

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 父模块 -->
    <div id="app">
      <h2>数字:{{num}}</h2>
      <cpn @increase="changeTotal" @reduce="changeTotal"></cpn>
    </div>

    <!-- 子模块 -->
    <template id="cpn">
      <div>
        <button @click="reduce">-1</button>
        <button @click="increase">+1</button>
      </div>
    </template>
    <script src="../vue.js"></script>
    <script>
      // 子组件
      const cpn = {
        template: "#cpn",
        data() {
          return {
            cnum: 0,
          };
        },
        methods: {
          // 发射事件,传给父级
          increase() {
            this.cnum++;
            this.$emit("increase", this.cnum);
          },
          reduce() {
            this.cnum--;
            this.$emit("reduce", this.cnum);
          },
        },
      };

      // Vue实例
      const app = new Vue({
        el: "#app",
        data: {
          num: 0,
        },
        components: {
          cpn,
        },
        methods: {
          changeTotal(cnum) {
            this.num = cnum;
            console.log(cnum);
          },
        },
      });
    </script>
  </body>
</html>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。