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

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 这种方式,因为它能提高代码的可维护性和可测试性。


http://www.kler.cn/a/594411.html

相关文章:

  • Docker 容器基础技术:namespace
  • wsl2配置xv6全解(包括22.04Jammy)
  • 人工智能在2025年:各行业现状与变革
  • 【大语言模型_6】mindie启动模型错误整理
  • Linux的I2C总线的原理和结构详解
  • 爬虫 crawler 入门爬取不设防网页 并实现无限增生
  • ip属地和手机定位区别在哪?是什么
  • Android 第四次面试总结(自定义 View 与事件分发深度解析)
  • [密码学实战]Java实现抗量子Kyber512与Dilithium2算法及详解
  • CAN通信转TCP/IP通信协议解析
  • 涨薪技术|Kubernetes(k8s)之Namespaces详解
  • MCU的应用场景:从智能家居到工业控制
  • Go语言--安装和环境搭配
  • 基于python的Flask模块化设计与蓝图的妙用——打造轻量化Web应用
  • 【QA】QT信号槽底层是怎么实现的?
  • sql server数据迁移,springboot搭建开发环境遇到的问题及解决方案
  • python视频转文本,音频转文本
  • Vue.js 性能优化:虚拟 DOM 与虚拟滚动
  • 太阳能地砖:绿色能源与城市美学的完美融合
  • 工艺品制造行业的现状 内检LIMS系统在工艺品制造的应用