Vue3?全局實例上掛載屬性方法案例講解
導語
在大多數(shù)開發(fā)需求中,我們有時需要將某個數(shù)據(jù),或者某個函數(shù)方法,掛載到,全局實例身上,以便于,在項目全局的任何位置都能夠調用其方法,或讀取其數(shù)據(jù)。
在Vue2 中,我們是在 main.js 中 直接將數(shù)據(jù)或者方法綁定在 Vue.prototype
身上,在頁面中,可以直接通過 this.事件名或數(shù)據(jù)名
就能夠拿到數(shù)據(jù)。
let art = () => { alert("事件方法") } import Vue from 'vue' Vue.prototype.$art = art
頁面中 通過 this 拿取到數(shù)據(jù)方法。
mounted() { this.$art() }
如今在 Vue3
中,結合了組合式 Api ,在 setup 函數(shù)中,我們無法獲取到 this,所以這樣的需求實現(xiàn),就得到了變更。 Vue3 提供了一個新的 Api globalProperties
,用來實現(xiàn)這樣的需求。
案例中,在 main.js 中定義好一個回調函數(shù)的方法。
import { createApp } from 'vue'; import App from './App.vue' const app = createApp(App) let art = () => { alert("事件方法") } app.config.globalProperties.art = art // 通過 globalProperties 將回調函數(shù)綁定在全局 app.mount('#app')
頁面中讀取 需要借助于使用 getCurrentInstance
Api 鉤子
方法一
:
<script setup> import { getCurrentInstance } from "vue" // 引用 getCurrentInstance // getCurrentInstance().appContext.config.globalProperties 獲取全局上下文,可以解構得到 我們前面綁定的數(shù)據(jù)方法 const { art } = getCurrentInstance().appContext.config.globalProperties let clicklogin = (formName) => { art() //直接調用方法本身 } </script>
方法二
:
<script setup> import { getCurrentInstance } from "vue" const { proxy } = getCurrentInstance() //獲取 getCurrentInstance 身上的 proxy 代理屬性 let clicklogin = (formName) => { proxy.art() //可以直接在 proxy代理屬性身上調用方法。 } </script>
有細心的小伙伴,會發(fā)現(xiàn) getCurrentInstance
這個Api 在官方文檔中,查詢不到,這是因為,在最新的V3 官方文檔中,對 getCurrentInstance
進行了移除。
至于為何現(xiàn)在還能使用,據(jù)說是現(xiàn)在 作為一個隱式的內(nèi)部 Api 使用
。
上面提到的方法,雖然可以通過 app.config.globalProperties
和 getCurrentInstance
來定義全局方法數(shù)據(jù),和讀取數(shù)據(jù),但是這種方法,并不推薦使用
,如下,官方的描述
相比于上面提到的方法,我們更推薦使用 provide
以及 inject
來實現(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 ,注入給后代實例 app.mount('#app')
頁面中:
<script setup> import { inject } from "vue" let art = inject("art") // 通過 inject 可以獲取到 全局實例上 通過 provide 所注入的參數(shù)值。 let clicklogin = (formName) => { art() } </script>
以上就是給大家?guī)淼?,有關于在 Vue3 中,如何實現(xiàn)全局掛載屬性方法。
到此這篇關于Vue3 全局實例上掛載屬性方法的文章就介紹到這了,更多相關Vue3掛載全局屬性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
在vue中使用inheritAttrs實現(xiàn)組件的擴展性介紹
這篇文章主要介紹了在vue中使用inheritAttrs實現(xiàn)組件的擴展性介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12如何用vue-cli3腳手架搭建一個基于ts的基礎腳手架的方法
這篇文章主要介紹了如何用vue-cli3腳手架搭建一個基于ts的基礎腳手架的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12Element-ui之ElScrollBar組件滾動條的使用方法
這篇文章主要介紹了Element-ui之ElScrollBar組件滾動條的使用方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-09-09