在Vue3的setup中如何使用this

在Vue3中,setup函数中的this指向的是undefined,因为setup函数是在组件实例化之前执行的,此时还没有this对象。因此,在setup函数中不能使用this关键字。

如果想要在setup函数中访问组件实例的属性或方法,可以使用Vue3提供的两个新的函数:getCurrentInstance和ctx。getCurrentInstance函数可以获取当前组件实例对象,而ctx则是一个包含了props、attrs、emit等属性和方法的上下文对象。

举个例子,如果有一个组件,其中有一个data属性和一个方法:

<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  data() {
    return {
      message: 'hello world'
    }
  },
  methods: {
    sayHello() {
      console.log('hello')
    }
  }
}
</script>

在setup函数中可以这样使用:

import { getCurrentInstance } from 'vue'

export default {
  setup() {
    const instance = getCurrentInstance()
    const message = instance.data.message
    const sayHello = instance.ctx.sayHello

    return {
      message,
      sayHello
    }
  }
}

在上面的例子中,我们通过getCurrentInstance函数获取了当前组件实例对象,并通过instance.data.message和instance.ctx.sayHello访问了组件实例的数据和方法。最终,我们将这些数据和方法作为对象返回,以供模板使用。

Logo

前往低代码交流专区

更多推荐