当前位置: 首页 > news >正文

vue3 setup中访问全局变量还用加this吗。原来在组合式API中,需要用this.$loading。在setup中怎么用

在 Vue 3 的 <script setup> 语法糖里,不存在 this 这个概念,因为 <script setup> 是一种更简洁的语法,它会自动将内部的变量和函数暴露给模板,并且不需要显式定义 setup 函数。若要访问全局变量,像之前组合式 API 里用 this.$loading 那样,有以下几种不同的处理方式。
1. 使用 getCurrentInstance 获取当前组件实例
可以借助 getCurrentInstance 函数来获取当前组件实例,进而访问全局属性。不过要注意,getCurrentInstance 返回的实例对象在生产环境和开发环境下的结构有所不同,且在严格模式下可能会有类型问题。

<template>
  <button @click="showLoading">显示加载中</button>
</template>

<script setup>
import { getCurrentInstance } from 'vue';

const instance = getCurrentInstance();

const showLoading = () => {
  if (instance) {
    // 访问全局属性 $loading
    instance.appContext.config.globalProperties.$loading.show();
  }
};
</script>

2. 通过 app.config.globalProperties 提前定义并使用
在创建 Vue 应用时,可提前把全局属性挂载到 app.config.globalProperties 上,然后在 <script setup> 里直接导入使用。
主应用文件(通常是 main.js 或 main.ts)

import { createApp } from 'vue';
import App from './App.vue';
import Loading from './Loading'; // 假设这是你的加载组件

const app = createApp(App);
// 挂载全局属性 $loading
app.config.globalProperties.$loading = Loading;
app.mount('#app');

组件文件

<template>
  <button @click="showLoading">显示加载中</button>
</template>

<script setup>
import { getCurrentInstance } from 'vue';

const instance = getCurrentInstance();

const showLoading = () => {
  if (instance) {
    const { $loading } = instance.appContext.config.globalProperties;
    $loading.show();
  }
};
</script>

3. 使用 provide 和 inject 进行依赖注入(推荐)
使用 provide 和 inject 可以更优雅地在组件间共享数据,避免直接访问全局属性带来的耦合问题。
主应用文件(提供数据)

import { createApp } from 'vue';
import App from './App.vue';
import Loading from './Loading'; // 假设这是你的加载组件

const app = createApp(App);
app.provide('$loading', Loading);
app.mount('#app');

组件文件(注入数据)

<template>
  <button @click="showLoading">显示加载中</button>
</template>

<script setup>
import { inject } from 'vue';

// 注入全局属性 $loading
const loading = inject('$loading');

const showLoading = () => {
  if (loading) {
    loading.show();
  }
};
</script>

通过上述方法,你就能在 Vue 3 的 <script setup> 里访问全局变量了。推荐使用 provide 和 inject 这种方式,因为它能提高代码的可维护性和可测试性。

相关文章:

  • 第1章:云原生时代:容器技术的发展历程与核心价值
  • 个人学习编程(3-19) leetcode刷题
  • Python 线程池
  • java-正则表达式-集合-泛型
  • VScode的debug
  • AUTOSAR与arxml的文档解析
  • 【Ratis】ratis-grpc支持零拷贝系列之引入ZeroCopyMessageMarshaller工具类
  • 【6】组合计数学习笔记
  • 2.FastAPI 中的路由与路径操作
  • Python中的字典:深度解析与应用实践
  • 破解验证码新利器:基于百度OCR与captcha-killer-modified插件的免费调用教程
  • 数据驱动进化:AI Agent如何重构手机交互范式?
  • CUDAOpenCV Hessain矩阵计算
  • 虚拟电商-延迟任务系统的微服务改造(二)
  • Linux内核Netfilter使用实战案例分析
  • 利用labelme进行图片标注
  • Redis BitMap 用户签到
  • numpy学习笔记12:实现数组的归一化(0-1范围)
  • 力扣 797. 所有可能的路径 解析JS、Java、python、Go、c++
  • 第2章:容器核心原理:深入理解Namespace、Cgroup与联合文件系统
  • Meta正为AI眼镜开发人脸识别功能
  • 司法部:持续规范行政执法行为,加快制定行政执法监督条例
  • 中国以“大幅开放市场”回应贸易保护主义
  • 美联储连续第三次维持利率不变,警示关税影响
  • 从“重规模”向“重回报”转变,公募基金迎系统性改革
  • 央行:全力推进一揽子金融政策加快落地