由于 Vue3 没有 Prototype 属性,所以需要在 main.ts 文件里使用 app.config.globalProperties 去定义全局函数和变量
Vue2:
// 之前 (Vue 2.x) Vue.prototype.$http = () => {}
// 之后 (Vue 3.x) const app = createApp({}) app.config.globalProperties.$http = () => {}
app.config.globalProperties.$env = "dev";
Vue3
Filters
app.config.globalProperties.$filters = { format<T extends any>(str: T): string { return `衔蝉-${str}`; } }
type Filter = { format<T>(str: T): string } // 声明要扩充@vue/runtime-core包的声明 // 这里扩充"ComponentCustomProperties"接口, 因为他是vue3中实例的属性的类型. declare module 'vue' { export interface ComponentCustomProperties { $filters: Filter; $env: string; } }
<template> <div>{{ $env }}</div> <div>{{ $filters.format("鲜花") }}</div> </template>
<script setup lang="ts"> import { ref, reactive, getCurrentInstance } from "vue"; // 读取当前实例 const app = getCurrentInstance(); console.log(app?.proxy?.$filters.format("TS")); console.log(app?.proxy?.$env); </script>
啊快发货快