Vue3学习之setup参数——面向初学者(二)

210 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第12天,点击查看活动详情

前情提要:上一篇简单介绍了setup函数、ref函数、reactive函数的简单使用,这一篇对setup函数进行更加深入的学习。

setup中的参数

setup中有两个参数,第一个参数是props,第二个是conText

  1. props:包含props配置声明且传入了的所有属性的对象,其实就是父组件给子组件传值,子组件使用props接收,props获取的就是父组件传入的所有属性对象;
  2. conText:返回的对象属性有attrs、slots、emit
    • attrs:包含没有在props配置中声明的属性的对象,相当于this.$attrs
    • slots:包含所有传入的插槽内容的对象,相当于this.$slots
    • emit:用来分发自定义事件的函数,相当于this.$emit 示例:

1.首先先创建一个子组件:

<template>
  <div>
    姓名:{{ name }}
    <div>年龄:{{ age }}</div>
  </div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "child",
  props: {
    name: {
      type: String,
      default: "",
    },
    age: {
      type: Number,
      default: "",
    },
  },
  setup(props, conText) {
    console.log(props.name, props.age); // 张三 26
    console.log(conText);
  },
});
</script>

2.父组件中引入,并传入值

<child name="张三" :age="26" gender="男">子组件插槽内容</child>

3.在setup中打印对应的参数

image.png

attrs

  • 如果需要获取gender的值,就是conText.attrs['gender']

slots

  • 如果需要获取组件插槽的内容,就用到了conTextslots

image.png 当直接调用的时候,会出现报错,这是因为ts的缘故,这时候需要把setup参数中的conText指定一个类型即可:

  setup(props, conText:any) {
    console.log(props.name, props.age);
    console.log(conText.slots.default());
  },

这时候插槽的内容就打印出来了:

image.png

  • emit的使用 子组件中通过sendValue方法发送内容:
<button @click="sendValue">给父组件传值</button>


  setup(props, conText: any) {
    let sendValue = () => {
      conText.emit("getValue", "我是子组件传过来的值");
    };
    return {
      sendValue,
    };
  },

父组件通过getValue接收传过来的值:

<template>
  <div>
    <child name="张三" :age="26" gender="男" @getValue="getChildValue"
      >子组件插槽内容</child
    >
  </div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import Child from "@/components/child.vue";
export default defineComponent({
  name: "setup",
  components: {
    Child,
  },
  setup() {
    let getChildValue = (val: string) => {
      console.log(val); // 我是子组件传过来的值
    };
    return {
      getChildValue,
    };
  },
});
</script>

emit

emit的用法和vue2中this.$emit的用法是一样的,只不过从this.$emit变成了conText.$emit

以上就是对setup中参数如何使用做的简单例子!

接下来继续学习Vue3的知识点~