×

Vue3 setup中如何获取this?

提问者:Terry2025.04.24浏览:81

首先明确在Vue3的setup函数里的情况

在Vue3中,setup函数是一个新的组件选项,它主要用于替代Vue2中的一些基于选项对象的配置方式,比如data、computed、methods等,但这里要注意哦,在setup函数内部,是没办法直接像在Vue2组件实例里那样使用this关键字来获取组件实例的。

为啥呢?因为setup函数在组件初始化阶段就被调用了,它的执行上下文和传统的基于this的组件实例上下文不太一样,它更像是一个独立的函数环境,主要是用来返回一些供模板使用或者给其他模块导入的属性和方法。

那如果真的想获取类似Vue2中this能获取到的一些信息怎么办呢?

其实呀,Vue3给我们提供了一些替代的办法来达到类似的效果呢。

(一)获取组件实例的props和attrs

如果想获取传入组件的props和attrs(也就是非props的属性),在setup函数里可以通过参数来获取哦,setup函数接收两个参数,第一个参数就是props,这里面就包含了父组件传递给当前组件的所有props数据啦,你可以直接像使用普通对象属性一样去使用里面的内容。

比如有个组件接收一个名为message的props:

<template>
  <div>{{ message }}</div>
</template>
<script>
import { defineComponent } from 'vue';
export default defineComponent({
  props: {
    message: String
  },
  setup(props) {
    // 这里就可以直接使用props.message啦
    console.log(props.message);
    return {
      // 也可以把它返回出去供模板使用哦
      message: props.message
    };
  }
});
</script>

而对于attrs,在Vue3里可以通过引入getCurrentInstance这个函数来获取,不过要注意哦,这个函数获取到的实例信息相对来说是比较底层的,在生产环境使用时要谨慎呢,尽量只在确实需要的情况下用。

示例如下:

<template>
  <div>{{ customAttr }}</div>
</template>
<script>
import { defineComponent, getCurrentInstance } from 'vue';
export default defineComponent({
  setup() {
    const instance = getCurrentInstance();
    if (instance) {
      const { attrs } = instance;
      // 这里就可以获取到非props的属性啦
      console.log(attrs.customAttr);
      return {
        customAttr: attrs.customAttr
      };
    }
    return {};
  }
});
</script>

(二)获取组件实例的上下文相关信息(比如emit等)

要是想在setup函数里触发一个自定义事件,就像在Vue2里通过this.$emit来做的那样,在Vue3里同样可以通过引入getCurrentInstance函数来获取到组件实例,然后从实例上拿到emit方法来触发事件哦。

比如有个组件要触发一个名为customEvent的自定义事件:

<template>
  <button @click="handleClick">点击触发事件</button>
</template>
<script>
import { defineComponent, getCurrentInstance } from 'vue';
export default defineComponent({
  setup() {
    const instance = getCurrentInstance();
    if (instance) {
      const { emit } = instance;
      const handleClick = () => {
        // 这里就可以触发自定义事件啦
        emit('customEvent', '传递一些数据哦');
      };
      return {
        handleClick
      };
    }
    return {};
  }
});
</script>

总结一下啦

在Vue3的setup函数里虽然不能像Vue2那样直接用this来获取组件实例相关的一切信息,但通过合理利用传入的props参数以及引入getCurrentInstance函数来获取attrs、emit等相关内容,也完全可以满足我们在组件开发过程中对类似功能的需求呀,所以呀,只要熟悉了这些新的方式,在Vue3的开发中也能很顺畅地实现各种功能呢。

您的支持是我们创作的动力!

网友回答文明上网理性发言 已有0人参与

发表评论: