目錄
一:基礎使用
1、簡介
2、使用
3、打印結果:
二:封裝
1、創建一個.ts文件(utils/msg.ts)
2、在main.ts中全局注冊
3、在頁面中使用
4、打印結果
一:基礎使用
1、簡介
app.config.globalProperties
?是 Vue 3 應用實例(app
)的一個配置屬性,它允許你在整個應用范圍內添加全局可用的屬性。將一些常用的工具函數掛載到全局屬性上,這樣在組件中就可以直接調用這些函數,而無需重復導入。
import { createApp } from 'vue';
import App from './App.vue';// 創建 Vue 應用實例
const app = createApp(App);// 添加全局屬性
app.config.globalProperties.$mes= '這是一個全局消息';
app.config.globalProperties.$meFunction=()=>{return '這是個全局函數返回的方法'
};// 掛載應用
app.mount('#app');
2、使用
<template><div></div>
</template><script setup lang="ts'>
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance() as any;
console.log("proxy", proxy);
console.log("mes", proxy.$mes);
console.log("msFunction", proxy.$meFunction());
</script>
解釋:
getCurrentInstance
?:?getCurrentInstance
?函數用于獲取當前正在活躍的組件實例。在 vue3的組合式 API 中,由于不再像選項式 API 那樣有一個明確的?this
?指向當前組件實例,當你需要訪問組件實例的屬性、方法或者上下文信息時,就可以使用?getCurrentInstance
?來獲取當前組件實例
proxy
?:?在 Vue 3 里,app.config.globalProperties
?可用于給應用添加全局屬性,而借助?getCurrentInstance
?獲取的?proxy
?對象能夠訪問這些全局屬性。
3、打印結果:
如果屬性很多,不可能全部寫在main.ts中,有以下方法
二:封裝
1、創建一個.ts文件(utils/msg.ts)
export const msgFunction = (value: any) => {return value;
};
2、在main.ts中全局注冊
import { createApp } from 'vue';
import App from './App.vue';// 創建 Vue 應用實例
const app = createApp(App);
import { msgFunction } from "./utils/msg";// 添加全局屬性
app.config.globalProperties.$msgFunction = msgFunction;// 掛載應用
app.mount('#app');
3、在頁面中使用
<template><div></div>
</template><script setup lang="ts'>
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance() as any;
console.log("proxy", proxy.$msgFunction("你好"));
</script>