欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3沒(méi)有this的解決方案

 更新時(shí)間:2024年07月12日 08:38:34   作者:苦夏木禾  
這篇文章主要介紹了vue3沒(méi)有this的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

vue3沒(méi)有this怎么辦

在vue3中,新的組合式API中沒(méi)有this,那我們?nèi)绻枰玫?code>this怎么辦?

解決方法

getCurrentInstance 方法獲取當(dāng)前組件的實(shí)例,然后通過(guò) ctxproxy 屬性獲得當(dāng)前上下文,這樣我們就能在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 函數(shù)中訪問(wèn) state
      count: computed(() => store.state.count),

      // 在 computed 函數(shù)中訪問(wèn) getter
      double: computed(() => store.getters.double)

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

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

大家不要依賴 getCurrentInstance 方法去獲取組件實(shí)例來(lái)完成一些主要功能,否則在項(xiàng)目打包后,一定會(huì)報(bào)錯(cuò)的。

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論