vue3沒(méi)有this的解決方案
vue3沒(méi)有this怎么辦
在vue3中,新的組合式API中沒(méi)有this,那我們?nèi)绻枰玫?code>this怎么辦?
解決方法
getCurrentInstance 方法獲取當(dāng)前組件的實(shí)例,然后通過(guò) ctx 或 proxy 屬性獲得當(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)文章
Vue3+TS實(shí)現(xiàn)動(dòng)態(tài)路由權(quán)限的示例詳解
當(dāng)我們?cè)陂_發(fā)一個(gè)大型的前端應(yīng)用時(shí),動(dòng)態(tài)路由權(quán)限是一個(gè)必不可少的功能,本文將介紹如何使用Vue 3和TypeScript來(lái)實(shí)現(xiàn)動(dòng)態(tài)路由權(quán)限,希望對(duì)大家有所幫助2024-01-01
Vue?編程式路由導(dǎo)航的實(shí)現(xiàn)示例
本文主要介紹了Vue?編程式路由導(dǎo)航2022-04-04
Vue異步請(qǐng)求導(dǎo)致頁(yè)面數(shù)據(jù)渲染錯(cuò)誤問(wèn)題解決方法示例
這篇文章主要為大家介紹了Vue中異步請(qǐng)求導(dǎo)致頁(yè)面數(shù)據(jù)渲染錯(cuò)誤問(wèn)題解決方法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09
vue中實(shí)現(xiàn)先請(qǐng)求數(shù)據(jù)再渲染dom分享
下面小編就為大家分享一篇vue中實(shí)現(xiàn)先請(qǐng)求數(shù)據(jù)再渲染dom分享,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-03-03

