app.config.globalProperties

发布于:2025-03-16 ⋅ 阅读:(16) ⋅ 点赞:(0)

目录

一:基础使用

1、简介

2、使用

3、打印结果:

二:封装

1、创建一个.ts文件(utils/msg.ts)

2、在main.ts中全局注册

3、在页面中使用

4、打印结果


一:基础使用

1、简介

app.config.globalProperties 是 Vue 3 应用实例(app)的一个配置属性,它允许你在整个应用范围内添加全局可用的属性。将一些常用的工具函数挂载到全局属性上,这样在组件中就可以直接调用这些函数,而无需重复导入。

import { createApp } from 'vue';
import App from './App.vue';

// 创建 Vue 应用实例
const app = createApp(App);

// 添加全局属性
app.config.globalProperties.$mes= '这是一个全局消息';
app.config.globalProperties.$meFunction=()=>{
   return '这是个全局函数返回的方法'
};

// 挂载应用
app.mount('#app');

2、使用

<template>
  <div>
    
  </div>
</template>

<script setup lang="ts'>
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance() as any;
console.log("proxy", proxy);
console.log("mes", proxy.$mes);
console.log("msFunction", proxy.$meFunction());
</script>

解释:

getCurrentInstance getCurrentInstance 函数用于获取当前正在活跃的组件实例。在 vue3的组合式 API 中,由于不再像选项式 API 那样有一个明确的 this 指向当前组件实例,当你需要访问组件实例的属性、方法或者上下文信息时,就可以使用 getCurrentInstance 来获取当前组件实例

proxy : Vue 3 里,app.config.globalProperties 可用于给应用添加全局属性,而借助 getCurrentInstance 获取的 proxy 对象能够访问这些全局属性。

3、打印结果:

如果属性很多,不可能全部写在main.ts中,有以下方法

二:封装

1、创建一个.ts文件(utils/msg.ts)

export const msgFunction = (value: any) => {
  return value;
};

2、在main.ts中全局注册

import { createApp } from 'vue';
import App from './App.vue';

// 创建 Vue 应用实例
const app = createApp(App);
import { msgFunction } from "./utils/msg";

// 添加全局属性
app.config.globalProperties.$msgFunction = msgFunction;

// 挂载应用
app.mount('#app');

3、在页面中使用

<template>
  <div>
    
  </div>
</template>

<script setup lang="ts'>
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance() as any;
console.log("proxy", proxy.$msgFunction("你好"));
</script>

4、打印结果