app.config.globalProperties

目录

一:基础使用

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、打印结果

相关推荐
zfyljx3 分钟前
五子棋html
前端·css·html
MossGrower9 分钟前
65.Three.js案例-使用 MeshNormalMaterial 和 MeshDepthMaterial 创建 3D 图形
javascript·threejs·spheregeometry·torusknotgeome
蓑笠翁0011 小时前
Python异步编程入门:从同步到异步的思维转变
linux·前端·python
程序员小杰@3 小时前
✨WordToCard使用分享✨
前端·人工智能·开源·云计算
larntin20023 小时前
vue2开发者sass预处理注意
前端·css·sass
Enti7c3 小时前
利用jQuery 实现多选标签下拉框,提升表单交互体验
前端·交互·jquery
SHUIPING_YANG4 小时前
在Fiddler中添加自定义HTTP方法列并高亮显示
前端·http·fiddler
互联网搬砖老肖4 小时前
Web 架构之前后端分离
前端·架构
pianmian15 小时前
坐标系与坐标系数转换
vue.js·html
水银嘻嘻5 小时前
web 自动化之 selenium+webdriver 环境搭建及原理讲解
前端·selenium·自动化