Vue3.0中this的替代方法

2,781 阅读1分钟

Vue3.0中this的替代方法

  • 在vue3中,新的组合式API中没有this,我们可以通过以下方法替代this
  • setup 在生命周期 beforecreate 和 created 前执行,此时 vue 对象还未创建,所以我们无法使用 this

方法一

getCurrentInstance() 方法,获取当前组件的实例,通过 ctx 或 proxy 属性获得当前上下文,从而就能在setup中使用router和vuex

import { getCurrentInstance } from "vue";
export default {
	setup() {
    	let { proxy } = getCurrentInstance();
    	console.log(proxy)
    }
}

在这里插入图片描述

getCurrentInstance 方法去获取组件实例来完成一些主要功能,在项目打包后,会报错(不推荐使用)

方法二(推荐使用)

import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
export default {
  setup () {
    const store = useStore()
	const route = useRoute()
    const router = useRouter()
    return {
      // 访问 state  函数
      count: computed(() => store.state.count),
      // 访问 getter函数
      double: computed(() => store.getters.double)
	  // mutation
      increment: () => store.commit('increment'),
      // 使用 action
      asyncIncrement: () => store.dispatch('asyncIncrement')
    }
  }
}

在这里插入图片描述