自学内容网 自学内容网

vue3 + TS 定义全局变量和方法

vue3 定义全局变量主要是利用组件实例中的 globalProperties 属性 来完成绑定。

1. 绑定赋值

我们直接来封装一个插件,方便后期管理。

  • global.ts
import type { App } from "vue";

const fn = () => "鱼钓猫的小鱼干";

export default {
  // 这里的 app 就是 main.ts 中创建的实例
  install(app: App) {
    app.config.globalProperties.$env = "dev";
    app.config.globalProperties.$fishingcat = fn;
  },
};
  • main.ts
import "./assets/main.css";
import { createApp } from "vue";

import App from "./App.vue";
// 引入插件
import global from "@/plugin/global";

const app = createApp(App);
// 注册插件
app.use(global);

app.mount("#app");

2. 应用

  • 绑定的全局变量或方法可以直接在任何组件中的 template 模版中直接使用。

index.vue

<template>
  <h1>{{ $env }}</h1>
  <h1>{{ $fishingcat() }}</h1>
</template>

我是效果图
在这里插入图片描述

  • ts 中需要在组件实例中访问。
<script setup lang="ts">

import { getCurrentInstance } from "vue";
const instance = getCurrentInstance();

// 在实例中的 proxy属性 上可以访问到所有的全局属性或方法
console.log(instance?.proxy?.$env); // "dev"

</script>

3. 完善

代码可以正常执行,但还有一点小问题:不存在该属性或方法。

在这里插入图片描述

这是因为,我们自定义的全局变量和方法缺少 类型声明 ,所以我们需要手动补充声明。
这是固定格式,在 ComponentCustomProperties 中定义类型。

declare module "@vue/runtime-core" {
  export interface ComponentCustomProperties {
    $env: string;
    $fishingcat: () => string;
  }
}

如果数量多的话,可以专门创建一个 ***.d.ts 文件去补充类型声明,这里我图省事直接写在一起了。

global.ts

import type { App } from "vue";

const fn = () => "鱼钓猫的小鱼干";

export default {
  install(app: App) {
    app.config.globalProperties.$env = "dev";
    app.config.globalProperties.$fishingcat = fn;
  },
};

declare module "@vue/runtime-core" {
  export interface ComponentCustomProperties {
    $env: string;
    $fishingcat: () => string;
  }
}

然后,一切恢复正常,完美结束!


原文地址:https://blog.csdn.net/weixin_62234646/article/details/142790295

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!