概述
globalProperties
定义全局函数和变量:vue2 的写法:
vue.prototype.$varName = () => {}
定义全局函数和变量:vue3 的写法:
const app = createApp(App)
app.config.globalProperties.$varName = () => {}
案例1:
main.ts
import { createApp} from 'vue'
const app = createApp(App)
type SAY = {
format: <T>(str: T) => string
}
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$varName: SAY,
$env: string
}
}
app.config.globalProperties.$varName = {
format<T>(str: T): string {
return 'say' + `${str}`
}
}
app.config.globalProperties.$env = 'dev'
index.vue
<template>
<div>
{{ $varName.format("Hello") }} - {{ $env }}
</div>
</template>
案例2:
读取全局配置的属性和方法,index.vue
<template>
<div>
{{$currentDate(1667220888000)}} - {{$name}}
</div>
</template>
<script setup lang='ts'>
import { onMounted, ref } from 'vue'
import defineGlobalStance from '@/assets/js/global'
const { globalConfig } = defineGlobalStance();
onMounted(() => {
console.log(globalConfig.$name)
console.log(globalConfig.$currentDate(1667220888000))
})
</script>
<style scoped>
</style>
main.ts:
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App)
import { currentDate } from './assets/js/index'
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$currentDate:<T>(str:T) => string
$name:string
}
}
app.config.globalProperties.$currentDate = currentDate
app.config.globalProperties.$name = "hello"
app.use(createPinia())
app.use(router)
app.mount('#app')
新建一个index.ts,用来公共管理声明方法:
export const currentDate = (data: number): string => {
const date = new Date(data)
let str = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
return str;
}
全局配置属性优化配置ts文件:
import { ComponentInternalInstance, getCurrentInstance} from "vue";
export default function globalCurrentInstance(){
const { appContext } = getCurrentInstance() as ComponentInternalInstance
const globalConfig = appContext.config.globalProperties
return{
globalConfig
}
}
这个时候,ComponentInternalInstance会报错,提示:
"ComponentInternalInstance" 是一种类型,在同时启用了 "preserveValueImports" 和 "isolatedModules" 时,必须使用仅类型导入进行导入。
解决办法:
找到根目录的tsconfig.app.json,然后把"preserveValueImports":false,关闭重启VSCode,即可:
{
"extends": "@vue/tsconfig/tsconfig.web.json",
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
"exclude": ["src/**/__tests__/*"],
"compilerOptions": {
"composite": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"preserveValueImports":false
}
}
最后
以上就是典雅滑板为你收集整理的vue3 - 21.定义全局函数&变量的全部内容,希望文章能够帮你解决vue3 - 21.定义全局函数&变量所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复