Vue3定义全局变量的方式总结(附代码)

教程下载地址: 网赚博客http://www.piaodoo.com/创业项目排行榜前十名http://www.piaodoo.com/


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;

/**定义变量 w e b s i t e ,并赋值为 d e v c u r s o r ∗ ∗ / a p p . c o n f i g . g l o b a l P r o p e r t i e s . website,并赋值为devcursor**/ app.config.globalProperties. 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 { KaTeX parse error: Expected 'EOF', got '}' at position 5: web }̲ = getCurrentIn…web)

/注意!getCurrentInstance()不能在回调函数、方法里使用/
//若要访问全局变量,需在函数外面调用getCurrentInstance()
const { proxy } = getCurrentInstance()
//或者
const name = getCurrentInstance().proxy.KaTeX parse error: Expected 'EOF', got '&' at position 31: …getUserInfo=()=&̲gt;{ console…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}`;
  }
}

总结 

到此这篇关于Vue3定义全局变量的方式总结的文章就介绍到这了,更多相关Vue3定义全局变量内容请搜索网赚博客http://www.piaodoo.com/以前的文章或继续浏览下面的相关文章希望大家以后多多支持网赚博客http://www.piaodoo.com/!

                        友情连接:  

茂名一技http://www.szsyby.net/


茂名一技http://www.enechn.com/


美文集http://www.tpyjn.cn/


手游排行前十名http://www.bjkhrx.com/

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值