Vue3 中組件傳值emit【Vue2.x向Vue3.x的遷移日記】


子組件

child.vue

<template>
  <div>
    <p>hello world</p>
    <button @click="handleClick">click</button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  emits: ["click"],
  setup(prop, context) {
    const handleClick = () => {
      context.emit("click");
    };
    return {
      handleClick
    };
  }
});
</script>

子組件中使用context.emit傳遞出去。

值得注意的是:emits

emits: ["click"]

將自定義的名稱需要再emits中聲明

 

父組件

father.vue

<template>
  <el-button type="primary" @click="setClick"></el-button>
</template>

<script lang="ts">
export default {
  setup() {
    const setClick = () => {
      console.log("click");
    };
    return { setClick };
  }
};
</script>

父組件還是一樣


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM