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

解决方法:

getCurrentInstance 方法获取当前组件的实例,然后通过 ctxproxy 属性获得当前上下文,这样我们就能在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 方法去获取组件实例来完成一些主要功能,否则在项目打包后,一定会报错的。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐