Vue3定義全局變量的方式總結(jié)(附代碼)
1、main.js 設(shè)置全局變量。
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App);
/** 定義一個(gè)函數(shù),用于對象鏈?zhǔn)饺≈?*/
const getObjChainingVal = (obj, keyName) => {
// ...
return tempObj
}
app.config.globalProperties.getObjChainingVal = getObjChainingVal;
/**定義變量$website,并賦值為devcursor**/
app.config.globalProperties.$website = 'devcursor';在其他頁面使用的時(shí)候
(1)在模板中使用:
<template>
<div>
作者:{{ getObjChainingVal(data, 'user.info.name') }}
<div>{{ $website }}</div>
</div>
</template>
(2)在語法糖<script setup>里使用:
<script setup>
import { getCurrentInstance } from 'vue'
const app = getCurrentInstance()
const website = app.appContext.config.globalProperties.$website
console.log(website)
// 或者
const { proxy } = getCurrentInstance()
console.log(proxy.$website)
// 使用解構(gòu)賦值
const { $web } = getCurrentInstance()!.appContext.config.globalProperties
console.log($web)
/**注意!getCurrentInstance()不能在回調(diào)函數(shù)、方法里使用**/
//若要訪問全局變量,需在函數(shù)外面調(diào)用getCurrentInstance()
const { proxy } = getCurrentInstance()
//或者
const name = getCurrentInstance().proxy.$website;
const getUserInfo=()=>{
console.log(proxy.$website);
console.log(name);
}
</script>
(3)組件實(shí)例中使用
<script>
export default {
mounted() {
console.log(this.$website) // 'devcursor'
}
}
</script>
2、使用provide定義變量、inject獲取變量
(1)父組件使用provide定義變量
import {provide} from "vue";
const data='hello Word';
provide('data',data);(2)子組件通過inject獲取變量
import {inject} from "vue";
const data=inject('data');
console.log(data,'555555555555555555555'); //輸出為:hello Word 附:定義全局函數(shù)Vue2 和 Vue3 的區(qū)別
由于 Vue3 沒有 Prototype 屬性,所以需要在 main.ts 文件里使用 app.config.globalProperties 去定義全局函數(shù)和變量
Vue2:
// 之前 (Vue 2.x)
Vue.prototype.$http = () => {}
Vue3:
// 之后 (Vue 3.x)
const app = createApp({})
app.config.globalProperties.$http = () => {}
定義一個(gè)全局變量,示例如下:
app.config.globalProperties.$env = "dev";
在 Vue3 移除了過濾器,定義一個(gè)全局函數(shù)代替 Filters,示例如下:
app.config.globalProperties.$filters = {
format<T extends any>(str: T): string {
return `銜蟬-${str}`;
}
}總結(jié)
到此這篇關(guān)于Vue3定義全局變量的方式總結(jié)的文章就介紹到這了,更多相關(guān)Vue3定義全局變量內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue-cli 項(xiàng)目打包完成后運(yùn)行文件路徑報(bào)錯(cuò)問題
這篇文章主要介紹了vue-cli 項(xiàng)目打包完成后運(yùn)行文件路徑報(bào)錯(cuò)問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
Vue中圖片上傳組件封裝-antd的a-upload二次封裝的實(shí)例
這篇文章主要介紹了Vue中圖片上傳組件封裝-antd的a-upload二次封裝的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
Vue項(xiàng)目實(shí)現(xiàn)token無感刷新的示例代碼
最近在使用系統(tǒng)的過程中,業(yè)務(wù)人員反饋剛登錄一會就提示token過期需要重新登錄,所以本文為大家分享一個(gè)無感刷新的實(shí)現(xiàn)代碼,需要的可以參考下2023-07-07
vue 綁定使用 touchstart touchmove touchend解析
這篇文章主要介紹了vue 綁定使用 touchstart touchmove touchend解析,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
vue修飾符v-model及.sync原理及區(qū)別詳解
這篇文章主要為大家介紹了vue修飾符v-model及.sync原理及使用區(qū)別詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07

