Vue3定义全局函数和变量

main.ts

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import mitt from 'mitt'

import Card from './components/Card/index.vue'

import ElementPlus from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'

import App from './App.vue'
import router from './router'
import './assets/reset.less'
const Mit = mitt()
const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

import * as func from './function'

//定义全局函数/变量
type Filter = {
  format: <T>(str: T) => string
  test: <T>() => string
}
declare module '@vue/runtime-core' {
  export interface ComponentCustomProperties {
    $filters: Filter
    $chunshu: string
    $func: Filter
  }
}
app.config.globalProperties.$filters = {
  format<T>(str: T): string {
    return `真.${str}`
  },
}
//导入外部全局函数
app.config.globalProperties.$func = func
//变量
app.config.globalProperties.$chunshu = 'intrwins'

app.component('Card', Card) //注册全局组件
app.use(ElementPlus)
app.use(createPinia())
app.use(router)
declare module 'vue' {
  export interface componentCustomProperties {
    $Bus: typeof Mit
  }
}
app.config.globalProperties.$Bus = Mit
app.mount('#app')

使用:

<template>
  <div>
    {{ $filters.format('我是渣男') }}
    {{ $chunshu }}
    {{ $func.test() }}
  </div>
</template>
<script setup lang="ts">
import Hook from './components/Hooks.vue'
</script>
<style scoped></style>

外部定义函数import * as func from './function':

export function test() {
  console.log('我是一个全局函数')
}



globalProperties

由于Vue3 没有Prototype 属性 使用 app.config.globalProperties 代替 然后去定义变量和函数


Vue2

// 之前 (Vue 2.x)
Vue.prototype.$http = () => {}

Vue3

// 之后 (Vue 3.x)
const app = createApp({})
app.config.globalProperties.$http = () => {}


关键词:
上一篇 下一篇


读后有收获可以支付宝请作者喝枸杞,有疑问也可以加作者讨论:





友情链接
@寅春树 豫ICP备20020705号 Powered by Thinkcmfx