子传父 vue3新特性

父组件 : 

<template>
  <div class="app">
    <h2>当前计数: {{ counter }}</h2>

    <!-- 1.自定义add-counter, 并且监听内部的add事件 -->
    <add-counter @add="addBtnClick"></add-counter>

  </div>
</template>

<script>
  import AddCounter from './AddCounter.vue'

  export default {
    components: {
      AddCounter,
    },
    data() {
      return {
        counter: 0
      }
    },
    methods: {
      addBtnClick(count) {
        this.counter += count
      },
    }
  }
</script>

<style scoped>
</style>
子组件 : 

<template>
  <div class="add">
    <button @click="btnClick(1)">+1</button>
    <button @click="btnClick(5)">+5</button>
    <button @click="btnClick(10)">+10</button>
  </div>
</template>

<script>
  export default {
    // 1.emits数组语法 - vue3先出现的,写了比较清楚,也有提示
    emits: ["add"],
    // 2.emmits对象语法 - vue3先出现的,写了比较清楚,也有提示
    emits: {
      add: function(count) {
        if (count <= 10) {
          return true
        }
        return false
      }
    },
    methods: {
      btnClick(count) {
        console.log("btnClick:", count)
        // 让子组件发出去一个自定义事件
        // 第一个参数自定义的事件名称
        // 第二个参数是传递的参数
        this.$emit("add", 100)
      }
    }
  }
</script>

<style scoped>
</style>

 

posted @ 2022-08-22 14:20  杨建鑫  阅读(96)  评论(0编辑  收藏  举报