Vue3定義全局變量的方式總結(jié)(附代碼)
1、main.js 設(shè)置全局變量。
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App);
/** 定義一個函數(shù),用于對象鏈式取值 */
const getObjChainingVal = (obj, keyName) => {
// ...
return tempObj
}
app.config.globalProperties.getObjChainingVal = getObjChainingVal;
/**定義變量$website,并賦值為devcursor**/
app.config.globalProperties.$website = 'devcursor';在其他頁面使用的時候
(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)組件實例中使用
<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 = () => {}
定義一個全局變量,示例如下:
app.config.globalProperties.$env = "dev";
在 Vue3 移除了過濾器,定義一個全局函數(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中圖片上傳組件封裝-antd的a-upload二次封裝的實例
這篇文章主要介紹了Vue中圖片上傳組件封裝-antd的a-upload二次封裝的實例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
vue 綁定使用 touchstart touchmove touchend解析
這篇文章主要介紹了vue 綁定使用 touchstart touchmove touchend解析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
vue修飾符v-model及.sync原理及區(qū)別詳解
這篇文章主要為大家介紹了vue修飾符v-model及.sync原理及使用區(qū)別詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07

