Vue3定义全局变量的方式总结
时间:2024-04-16 07:30:42 来源:网络cs 作者:欧阳逸 栏目:卖家故事 阅读:
阅读本书更多章节>>>>
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.$websiteconsole.log(website)// 或者const { proxy } = getCurrentInstance()console.log(proxy.$website)// 使用解构赋值const { $web } = getCurrentInstance()!.appContext.config.globalPropertiesconsole.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
阅读本书更多章节>>>>
本文链接:https://www.kjpai.cn/gushi/2024-04-16/159272.html,文章来源:网络cs,作者:欧阳逸,版权归作者所有,如需转载请注明来源和作者,否则将追究法律责任!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
上一篇:Chatgpt掘金之旅—有爱AI商业实战篇|专业博客|(六)
下一篇:返回列表