Vue3中setup细节

本文详细介绍了Vue3中的setup函数,包括其在beforeCreate之前的执行时机,返回值通常是一个对象用于提供组件数据和方法,以及setup的参数如props、attrs、slots和emit的用法。
摘要由CSDN通过智能技术生成

1. setup 执行的时机

  1. 在 beforeCreate 之前执行(一次), 此时组件对象还没有创建
  2. this 是 undefined, 不能通过 this 来访问 data/computed/methods / props
  3. 其实所有的 composition API 相关回调函数中也都不可以

2. setup 的返回值

  1. 一般都返回一个对象: 为模板提供数据, 也就是模板中可以直接使用此对象中的所有属性/方法
  2. 返回对象中的属性会与 data 函数返回对象的属性合并成为组件对象的属性
  3. 返回对象中的方法会与 methods 中的方法合并成功组件对象的方法
  4. 如果有重名, setup 优先

注意:
一般不要混合使用: methods 中可以访问 setup 提供的属性和方法, 但在 setup 方法中不能访问 data 和 methods
setup 不能是一个 async 函数: 因为返回值不再是 return 的对象, 而是 promise, 模板看不到 return 对象中的属性数据

3. setup 的参数

  1. setup(props, context) / setup(props, {attrs, slots, emit})
  2. props: 父组件传给子组件的属性(在子组件中通过 props 声明过的属性)
  3. attrs: 没有在子组件中通过 props 声明过的属性, 相当于 this.$attrs
  4. slots: 包含所有传入的插槽内容的对象, 相当于 this.$slots
  5. emit: 用来分发自定义事件的函数, 相当于 this.$emit
<template>
  <h2>App</h2>
  <p>msg: {{msg}}</p>
  <button @click="fn('--')">更新</button>

  <child :msg="msg" msg2="cba" @fn="fn" />
</template>

<script lang="ts">
  import { reactive, ref } from "vue";
  import child from "./child.vue";

  export default {
    components: {
      child,
    },

    setup() {
      const msg = ref("abc");

      function fn(content: string) {
        msg.value += content;
      }
      return {
        msg,
        fn,
      };
    },
  };
</script>
<template>
  <div>
    <h3>{{n}}</h3>
    <h3>{{m}}</h3>

    <h3>msg: {{msg}}</h3>
    <h3>msg2: {{$attrs.msg2}}</h3>

    <slot name="xxx"></slot>

    <button @click="update">更新</button>
  </div>
</template>

<script lang="ts">
  import { ref, defineComponent } from "vue";

  export default defineComponent({
    name: "child",

    props: ["msg"],

    emits: ["fn"], // 可选的, 声明了更利于程序员阅读, 且可以对分发的事件数据进行校验

    data() {
      console.log("data", this);
      return {
        // n: 1
      };
    },

    beforeCreate() {
      console.log("beforeCreate", this);
    },

    methods: {
      // update () {
      //   this.n++
      //   this.m++
      // }
    },

    // setup (props, context) {
    setup(props, { attrs, emit, slots }) {
      console.log("setup", this);
      console.log(props.msg, attrs.msg2, slots, emit);

      const m = ref(2);
      const n = ref(3);

      function update() {
        // console.log('--', this)
        // this.n += 2
        // this.m += 2

        m.value += 2;
        n.value += 2;

        // 分发自定义事件
        emit("fn", "++");
      }

      return {
        m,
        n,
        update,
      };
    },
  });
</script>
  • 24
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值