【Vue3】定义全局变量和全局函数

// main.ts
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)

// 解决 ts 报错
type Filter = {
  format<T>(str: T): string
}
declare module 'vue' {
  export interface ComponentCustomProperties {
    $filters: Filter,
    $myArgs: string
  }
}

app.config.globalProperties.$myArgs = 'args'
app.config.globalProperties.$filters = {
  format<T>(str: T) {
    return `xiuxiu-${str}`
  }
}
app.mount('#app')

<template>
  <div>
    {{ $myArgs }}
    <hr>
    {{ $filters.format('的杯子') }}
  div>
template>

<script setup lang="ts">
import { getCurrentInstance } from 'vue';
const app = getCurrentInstance()
// 利用组件实例输出{{ $filter.format('的杯子') }}
console.log(app?.proxy?.$filters.format('的杯子'));
script>

<style scoped>style>

【Vue3】定义全局变量和全局函数_第1张图片

你可能感兴趣的:(Vue,vue.js,javascript,前端)