
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 的区别
由于 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}`; } }
大家可以试试。





网友评论文明上网理性发言 已有0人参与
发表评论: