最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Vue3?全局實(shí)例上掛載屬性方法案例講解

 更新時(shí)間:2023年05月03日 10:53:43   作者:舊夢(mèng)星軌  
這篇文章主要介紹了Vue3?全局實(shí)例上掛載屬性方法,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

導(dǎo)語(yǔ)

在大多數(shù)開發(fā)需求中,我們有時(shí)需要將某個(gè)數(shù)據(jù),或者某個(gè)函數(shù)方法,掛載到,全局實(shí)例身上,以便于,在項(xiàng)目全局的任何位置都能夠調(diào)用其方法,或讀取其數(shù)據(jù)。

在Vue2 中,我們是在 main.js 中 直接將數(shù)據(jù)或者方法綁定在 Vue.prototype 身上,在頁(yè)面中,可以直接通過 this.事件名或數(shù)據(jù)名 就能夠拿到數(shù)據(jù)。

let art = () => {
  alert("事件方法")
}
import Vue from 'vue'
Vue.prototype.$art = art

頁(yè)面中 通過 this 拿取到數(shù)據(jù)方法。

    mounted() {
        this.$art()
    }

如今在 Vue3 中,結(jié)合了組合式 Api ,在 setup 函數(shù)中,我們無法獲取到 this,所以這樣的需求實(shí)現(xiàn),就得到了變更。 Vue3 提供了一個(gè)新的 Api globalProperties,用來實(shí)現(xiàn)這樣的需求。

案例中,在 main.js 中定義好一個(gè)回調(diào)函數(shù)的方法。

import { createApp } from 'vue';
import App from './App.vue'
const app = createApp(App)
let art = () => {
  alert("事件方法")
}
app.config.globalProperties.art = art      //  通過 globalProperties  將回調(diào)函數(shù)綁定在全局
app.mount('#app')

頁(yè)面中讀取 需要借助于使用 getCurrentInstance Api 鉤子

方法一

<script setup>
import { getCurrentInstance } from "vue"   // 引用 getCurrentInstance
//  getCurrentInstance().appContext.config.globalProperties 獲取全局上下文,可以解構(gòu)得到 我們前面綁定的數(shù)據(jù)方法
const { art } = getCurrentInstance().appContext.config.globalProperties
let clicklogin = (formName) => {
  art()     //直接調(diào)用方法本身
}
</script>

方法二

<script setup>
import { getCurrentInstance } from "vue"
const { proxy } = getCurrentInstance()    //獲取 getCurrentInstance 身上的 proxy 代理屬性
let clicklogin = (formName) => {
  proxy.art()           //可以直接在 proxy代理屬性身上調(diào)用方法。
}
</script>

有細(xì)心的小伙伴,會(huì)發(fā)現(xiàn) getCurrentInstance 這個(gè)Api 在官方文檔中,查詢不到,這是因?yàn)?,在最新的V3 官方文檔中,對(duì) getCurrentInstance 進(jìn)行了移除。

至于為何現(xiàn)在還能使用,據(jù)說是現(xiàn)在 作為一個(gè)隱式的內(nèi)部 Api 使用。

上面提到的方法,雖然可以通過 app.config.globalPropertiesgetCurrentInstance 來定義全局方法數(shù)據(jù),和讀取數(shù)據(jù),但是這種方法,并不推薦使用,如下,官方的描述

相比于上面提到的方法,我們更推薦使用 provide 以及 inject 來實(shí)現(xiàn)全局掛載數(shù)據(jù)方法。

在main.js 中

import { createApp } from 'vue';
import App from './App.vue'
const app = createApp(App)
let art = () => {
  alert("事件方法")
}
app.provide("art", art)    //將要掛載的參數(shù), 通過 provide ,注入給后代實(shí)例
app.mount('#app')

頁(yè)面中:

<script setup>
import { inject } from "vue"
let art = inject("art")      //  通過 inject 可以獲取到 全局實(shí)例上 通過 provide  所注入的參數(shù)值。
let clicklogin = (formName) => {
    art()
}
</script>

以上就是給大家?guī)淼模嘘P(guān)于在 Vue3 中,如何實(shí)現(xiàn)全局掛載屬性方法。

到此這篇關(guān)于Vue3 全局實(shí)例上掛載屬性方法的文章就介紹到這了,更多相關(guān)Vue3掛載全局屬性內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

古丈县| 灵山县| 通许县| 胶南市| 涞水县| 珲春市| 时尚| 莒南县| 邢台县| 邢台市| 汤阴县| 汉阴县| 永宁县| 九台市| 伊通| 蒙山县| 卢氏县| 绵竹市| 南乐县| 应城市| 深水埗区| 宿迁市| 多伦县| 洛隆县| 唐河县| 灵丘县| 阿拉尔市| 平定县| 湖南省| 上饶县| 七台河市| 垣曲县| 阳江市| 白水县| 新郑市| 武隆县| 尉氏县| 汾阳市| 阳谷县| 遂平县| 怀柔区|