vue3 - 全局函数和变量

65 阅读1分钟

全局函数和变量

image.png

main.ts

import { createApp } from 'vue';

import App from './App.vue';

const app = createApp(App);

// 扩充声明
declare module 'vue' {
  export interface ComponentCustomProperties {
    $filter: {
      format: <T>(str: T) => string;
    };
    $env: string;
  }
}
// 注册全局函数和变量
app.config.globalProperties.$env = import.meta.env.MODE;
app.config.globalProperties.$filter = {
  format: <T>(v: T) => {
    return `${v}-add some thing`;
  },
};

app.mount('#app');

组件使用

<template>
  <div style="border: 1px solid black; height: 500px; background-color: #3dc9b0">
    我是C
    <hr />
    <div>{{ $env }}</div>
    <div>{{ $filter.format('menffy') }}</div>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance } from 'vue';

// 获取当前组件实例
const app = getCurrentInstance();
// 调用
console.log(app.proxy.$env);
console.log(app.proxy.$filter.format('menffy2'));

</script>

<style scoped></style>

image.png