当前位置: 代码网 > it编程>编程语言>Javascript > Vue3定义全局变量的方式总结(附代码)

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

2024年05月15日 Javascript 我要评论
1、main.js 设置全局变量。import { createapp } from 'vue'import app from './app.vue'const app = createapp(app

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

总结 

到此这篇关于vue3定义全局变量的方式总结的文章就介绍到这了,更多相关vue3定义全局变量内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com