vue獲取組件實(shí)例
選項(xiàng)式獲取組件實(shí)例
在選項(xiàng)式中可以直接通過this
來獲取組件實(shí)例,通過this
來訪問實(shí)例對(duì)象的各種方法
//該組件實(shí)例管理的 DOM 根節(jié)點(diǎn)。
this.$el
//表示組件當(dāng)前已解析的 props 對(duì)象。
this.$props
//數(shù)據(jù)
this.$data
//父組件實(shí)例
this.$parent
//根組件實(shí)例
this.$root
//插槽對(duì)象
this.$slots
//一個(gè)包含 DOM 元素和組件實(shí)例的對(duì)象
this.$refs
//其他屬性:https://cn.vuejs.org/api/component-instance.html
組合式中獲取組件實(shí)例
在組合式用,代碼都寫在setup函數(shù)中,無法通過this
獲取組件實(shí)例,需要通過getCurrentInstance()
方法,getCurrentInstance()
獲取的實(shí)例對(duì)象和選項(xiàng)式獲取組件實(shí)例不同
<script lang='ts'>
import { defineComponent,getCurrentInstance} from 'vue';
export default defineComponent({
setup(props, { attrs, slots, emit, expose }) {
const instance = getCurrentInstance()
}
})
</script>
和選項(xiàng)式相同的含$的實(shí)例對(duì)象
在選項(xiàng)式中的實(shí)例的屬性都含$
符號(hào),在組合式中需要通過proxy
這個(gè)對(duì)象來獲取選項(xiàng)式中的實(shí)例,也就是說選項(xiàng)式中的實(shí)例對(duì)象在組合式中,屬于是組合式實(shí)例對(duì)象的proxy
成員變量
const instance = getCurrentInstance()
const proxy = instance.proxy
//該組件實(shí)例管理的 DOM 根節(jié)點(diǎn)。
proxy.$el
//表示組件當(dāng)前已解析的 props 對(duì)象。
proxy.$props
//數(shù)據(jù)
proxy.$data
//父組件實(shí)例
proxy.$parent
//根組件實(shí)例
proxy.$root
//插槽對(duì)象
proxy.$slots
//一個(gè)包含 DOM 元素和組件實(shí)例的對(duì)象
proxy.$refs
//其他屬性:https://cn.vuejs.org/api/component-instance.html
//true
console.log(instance.parent.proxy == instance.proxy.$parent);
實(shí)例對(duì)象的ctx屬性問題
在組合式中實(shí)例的ctx屬性在生產(chǎn)環(huán)境中是無法獲取的,也就是說,想獲取上下文對(duì)象,應(yīng)該在setup
函數(shù)中獲取
錯(cuò)誤做法
//開發(fā)環(huán)境能獲取,但在生產(chǎn)中ctx為空
const { ctx } = getCurrentInstance() //×
正確做法
setup(props,ctx){}
getCurrentInstance被標(biāo)記為non-public APIs
https://github.com/vuejs/docs/issues/1422,盡管getCurrentInstance
是非公開API但是你依舊可以使用它,因?yàn)樗莾?nèi)部實(shí)例,在你開發(fā)vue組件庫時(shí)依舊可以使用。
在vue的官方文檔中找不到getCurrentInstance()
,是因?yàn)檫@方法是內(nèi)部方法
Because the instance is an internal instance that exposes non-public APIs. Anything you use from that instance can technically break between any release types, since they are not subject to semver constraints.
I’m not sure why you need the setup context in nested composables, but explicitly passing arguments to composables make then less coupled to the consuming component, thus easier to understand and test in isolation.文章來源:http://www.zghlxwxcb.cn/news/detail-467618.html
In general a library designed to work with Composition API should expose special variables via its own composables (e.g.
useRoute
fromvue-router
) instead of the requiring the user to grab it from the instance.文章來源地址http://www.zghlxwxcb.cn/news/detail-467618.html
到了這里,關(guān)于vue獲取組件實(shí)例的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!