Vue3定义全局变量的方式总结

慈云数据 8个月前 (03-12) 技术支持 119 0

1、main.js 设置全局变量

Vue3定义全局变量的方式总结
(图片来源网络,侵删)
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)在模板中使用:

Vue3定义全局变量的方式总结
(图片来源网络,侵删)
  
    作者:{{ getObjChainingVal(data, 'user.info.name') }}
    {{ $website }}
  

(2)在语法糖里使用:

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);
}

(3)组件实例中使用

export default {
  mounted() {
    console.log(this.$website) // 'devcursor'
  }
}

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 
微信扫一扫加客服

微信扫一扫加客服

点击启动AI问答
Draggable Icon