vue3學習之 父子傳參以及setup的使用


父組件vue3parent

<template>
  <children msg="父親像兒子傳遞一句話" @sayhello="childToParentEmit">
    <!-- 傳遞一個帶名字的插槽 aaa為插槽名字-->
    <!-- 在vue3中盡量用v-slot的方式  在自組件內使用context.slot時才會打印出插槽名字 -->
    <template v-slot:aaa>
      <span></span>
    </template>
  </children>
</template>
<script>
import children from "./vue3children";
export default {
  name: "vue3parent",
  components: {
    children
  },
  setup() {
    function childToParentEmit(value) {
      //  傳遞過來的值用一個參數接收
      console.log("我是子組件傳遞過來的事件", vavue3childrenlue);
    }
    // 在vue3中 聲明的方法也要return出去 否則訪問不到
    return {
      childToParentEmit
    };
  }
};
</script>

子組件vue3children

<template>
  <div>
    <!-- 可以直接使用傳遞過來的props里面的信息 -->
    {{msg}}
    <button @click="text">測試觸發一下子向父傳遞信息</button>
  </div>
</template>
<script>
export default {
  name: "vue3children",
  //   vue3接收父親傳遞過來的消息 也需要用props接受
  // 也可以用對象形式  指定類型和默認值
  props: ["msg"],
  // vue3使用emit時,需用一個emits聲明一下傳遞過來的事件,不然會有警告
  emits:['sayhello'],
  // setup會接收兩個參數 props 和 context
  setup(props, context) {
    console.log(props, context);
    // context 里面主要有三個屬性需要了解
    // context.attrs  相當於vue2中的this.$attrs
    // context.emit   相當於vue2中的this.$emit
    // context.slots  插槽 相當於this.$slots
    function text() {
      // 子組件象父組件觸發事件傳遞信息
      context.emit("text", 666);
    }, 
    return {
      text
    }
  }
};
</script>


免責聲明!

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



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