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>

posted @ 2022-02-11 15:40  爱喝可乐的靓仔  阅读(1067)  评论(0编辑  收藏  举报