Vue3定義全局變量的方式總結(附代碼)
更新時間:2024年04月03日 10:43:40 作者:前端愛好者lxy
vue創(chuàng)建全局變量和方法有很多種,下面這篇文章主要給大家介紹了關于Vue3定義全局變量的方式,文中通過代碼介紹的非常詳細,對大家學習或者使用vue3具有一定的參考借鑒價值,需要的朋友可以參考下
1、main.js 設置全局變量。
import { createApp } from 'vue' import App from './App.vue' const app = createApp(App); /** 定義一個函數,用于對象鏈式取值 */ 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) // 使用解構賦值 const { $web } = getCurrentInstance()!.appContext.config.globalProperties console.log($web) /**注意!getCurrentInstance()不能在回調函數、方法里使用**/ //若要訪問全局變量,需在函數外面調用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
附:定義全局函數Vue2 和 Vue3 的區(qū)別
由于 Vue3 沒有 Prototype 屬性,所以需要在 main.ts 文件里使用 app.config.globalProperties 去定義全局函數和變量
Vue2:
// 之前 (Vue 2.x) Vue.prototype.$http = () => {} Vue3: // 之后 (Vue 3.x) const app = createApp({}) app.config.globalProperties.$http = () => {} 定義一個全局變量,示例如下: app.config.globalProperties.$env = "dev";
在 Vue3 移除了過濾器,定義一個全局函數代替 Filters,示例如下:
app.config.globalProperties.$filters = { format<T extends any>(str: T): string { return `銜蟬-${str}`; } }
總結
到此這篇關于Vue3定義全局變量的方式總結的文章就介紹到這了,更多相關Vue3定義全局變量內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue中圖片上傳組件封裝-antd的a-upload二次封裝的實例
這篇文章主要介紹了Vue中圖片上傳組件封裝-antd的a-upload二次封裝的實例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09vue 綁定使用 touchstart touchmove touchend解析
這篇文章主要介紹了vue 綁定使用 touchstart touchmove touchend解析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03vue修飾符v-model及.sync原理及區(qū)別詳解
這篇文章主要為大家介紹了vue修飾符v-model及.sync原理及使用區(qū)別詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07