vscode——VUE 父子组件通信-子传父实例(计数器)

b站 vue.js视频中的案例成果如下:

 

 主要功能:

1."+1"和"-1"控制下面的数字

2.减到0时,"-1"按钮消失

3.利用子传父的通信实现

代码如下:

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>test</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>
  <div id="app">
    <child @fa-add = "chage" @fa-minus = "chage"></child>
    <h2>当前次数:{{num}}</h2>
  </div>

  <template id="cpn">
    <div>
      <button @click = "add">+1</button>
      <button @click = "minus" :disabled = "number <= 0">-1</button>
    </div>
  </template>

  <script>

    var app= new Vue({
      el: '#app',
      data: {
        num:0
      },
        methods: {
          chage(number){
            this.num = number
          }
        },
        components:{
          'child':{
            template:"#cpn",
            data() {
              return {
                number:0
              }
            },
            methods: {
              add(){
                this.number++;
                this.$emit('fa-add',this.number)
              },
              minus(){
              this.number--;
              this.$emit('fa-minus',this.number)
              }
            }
          }
        }
    })
  </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_44901175/article/details/107550074