vue3没有this怎么办?

文章讲述了在Vue3的新API中如何在setup中处理this的问题,推荐使用`getCurrentInstance`获取实例的proxy来间接访问router和vuex,但强调不建议这样做,提倡在setup中使用计算属性(computed)、store、route和router的导出函数,以避免在打包后可能遇到的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在vue3中,新的组合式API中没有this,那我们如果需要用到this怎么办?

解决方法:
getCurrentInstance 方法获取当前组件的实例,然后通过 ctx 或 proxy 属性获得当前上下文,这样我们就能在setup中使用router和vuex了

import { getCurrentInstance } from "vue";
export default {
	setup() {
    	let { proxy } = getCurrentInstance();
    	proxy.$axios(...)
    	proxy.$router(...)
    }
}

但是
但是,不建议使用,如果要使用router和vuex,推荐这样用:

import { computed } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
export default {
  setup () {
    const store = useStore()
	const route = useRoute()
    const router = useRouter()
    return {
      // 在 computed 函数中访问 state
      count: computed(() => store.state.count),

      // 在 computed 函数中访问 getter
      double: computed(() => store.getters.double)

	  // 使用 mutation
      increment: () => store.commit('increment'),

      // 使用 action
      asyncIncrement: () => store.dispatch('asyncIncrement')
    }
  }
}

大家不要依赖 getCurrentInstance 方法去获取组件实例来完成一些主要功能,否则在项目打包后,一定会报错的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值