目錄
- Vue3使用this
- 具體使用如下:
- 補(bǔ)充:Vue3.0中this的替代方法
- 方法一
- 方法二(推薦使用)
- 總結(jié)
Vue3使用this
Vue2升級(jí)到Vue3,有很大的改變,其中最明顯的就是以前的this,在新版本中無法使用了,這是為什么呢?
官方是這樣說的:在?setup()?內(nèi)部,this?不會(huì)是該活躍實(shí)例的引用(即不指向vue實(shí)例),因?yàn)?setup()?是在解析其它組件選項(xiàng)之前被調(diào)用的,所以?setup()?內(nèi)部的?this?的行為與其它選項(xiàng)中的?this?完全不同。這在和其它選項(xiàng)式?API?一起使用?setup()?時(shí)可能會(huì)導(dǎo)致混淆。
因此setup函數(shù)中不能使用this。所以Vue為了避免我們錯(cuò)誤的使用,直接將setup函數(shù)中的this修改成了 undefined
所以想要在Vue3中使用this, Vue為我們提供了getCurrentInstance()方法,這個(gè)方法返回了ctx和proxy。
具體使用如下:
<script setup> import {getCurrentInstance} from '@vue/runtime-core' const currentInstance = ref() onMounted(() => { /** * 此處這樣使用時(shí)因?yàn)閂ue3不同于Vue2,在 Vue3的setup中我們是無法訪問到this的,所以我們需要借助一個(gè)方法, * 那就是getCurrentInstance,該方法返回了當(dāng)前的實(shí)例對(duì)象 * * 注意!!!!! * 不要把該函數(shù)當(dāng)作是optionsApi中來獲取 this 使用。 * 該方法只在 setup、生命周期函數(shù)中有效,在方法中是無效的 * */ currentInstance.value = getCurrentInstance() }); </script>
這樣我們就可以借助currentInstance 來完成在Vue2中this的使用場(chǎng)景了
補(bǔ)充:Vue3.0中this的替代方法
- 在vue3中,新的組合式API中沒有this,我們可以通過以下方法替代this
- setup 在生命周期 beforecreate 和 created 前執(zhí)行,此時(shí) vue 對(duì)象還未創(chuàng)建,所以我們無法使用 this
方法一
getCurrentInstance() 方法,獲取當(dāng)前組件的實(shí)例,通過 ctx 或 proxy 屬性獲得當(dāng)前上下文,從而就能在setup中使用router和vuex
import { getCurrentInstance } from "vue";
export default { setup() { let { proxy } = getCurrentInstance(); console.log(proxy) } }
getCurrentInstance 方法去獲取組件實(shí)例來完成一些主要功能,在項(xiàng)目打包后,會(huì)報(bào)錯(cuò)(不推薦使用)
方法二(推薦使用)
import { useStore } from 'vuex' import { useRoute, useRouter } from 'vue-router'
export default { setup () { const store = useStore() const route = useRoute() const router = useRouter() return { // 訪問 state 函數(shù) count: computed(() => store.state.count), // 訪問 getter函數(shù) double: computed(() => store.getters.double) // mutation increment: () => store.commit('increment'), // 使用 action asyncIncrement: () => store.dispatch('asyncIncrement') } } }
總結(jié)
到此這篇關(guān)于Vue3中使用this的文章就介紹到這了,更多相關(guān)Vue3使用this內(nèi)容請(qǐng)搜索技圈網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持技圈網(wǎng)!