使用之因
一般我們在vue開發(fā)中,常用的功能,接口等等我們都會封裝起來,如何每次創(chuàng)建一個組件,想要使用這些封裝起來的功能、接口等等都需要先引入,再通過層層調(diào)用才可以得到結(jié)果,如果我現(xiàn)在一遍需要調(diào)用后端接口、驗證n種輸入框,且這些方法都不在同一個文件當中,我們就需要不斷引入,相當麻煩。所以就會想著能否將這些常用的,都存放在一塊,需要調(diào)用的時候,只需要引入一個,既可得到所有分裝起來的功能。
使用之果
注意:如果全局屬性與組件自己的屬性沖突,組件自己的屬性將具有更高的優(yōu)先級。
1、創(chuàng)建一個文件(通過useGlobelProperties獲取全局屬性)
useGlobelProperties.ts
?
import { ComponentInternalInstance, getCurrentInstance } from "vue"; ?
export default function useGlobelProperties(){
? ?const { appContext } = getCurrentInstance() as ComponentInternalInstance; ? //??
? ?return appContext.config.globalProperties; ? ?//??
}
2、在main.ts中(配置全局屬性)
const app = createApp(App);
app.config.globalProperties.name = "你好"; ? //??
app.use(ElementPlus).mount("#app");
3、任意組件中的使用
//引入useGlobelProperties.ts,并將方法useGlobelProperties 解析出來
import useGlobelProperties from './useGlobelProperties'
const that = useGlobelProperties()
console.log(that)
打印所得:?文章來源:http://www.zghlxwxcb.cn/news/detail-551309.html
?可以看到我們上面定義的name可以拿到,后續(xù)想要什么全局配置,可以自行嘗試添加($xxx)文章來源地址http://www.zghlxwxcb.cn/news/detail-551309.html
到了這里,關(guān)于Vue3之a(chǎn)pp.config.globalProperties(定義全局變量)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!