Vue3 defines global properties and methods and uses them in components to solve the problem of error reporting in building

Defining global properties and methods needs to be defined in main.ts: for example, define a variable env and a function filter here 

// 定义全局变量和全局函数
app.config.globalProperties.env = "dev"

app.config.globalProperties.filter = {
  format<T>(content:T){
    return "格式化后的内容" + content
  }
}

Then in the Vue component

Although there is normal rendering on the page, there is a lack of error in the template:  the reason for the error is that the attribute env cannot be found, so you need to declare this variable and function in main.ts

Solve the error that the variable and function cannot be found

Declare it in main.ts:

import './assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
import router from './router'

const app = createApp(App)

app.use(createPinia())
app.use(router)

app.use(ElementPlus)
// 定义全局变量和全局函数
app.config.globalProperties.env = "dev"

app.config.globalProperties.filter = {
  format<T>(content:T){
    return "格式化后的内容" + content
  }
}

// 解决Vue中的全局变量和函数报错问题
interface Filter {
  format<T>(content:T):string
}
declare module 'vue' {
  export interface ComponentCustomProperties {
    filter: Filter,
    env:string
  }
}



app.mount('#app')

After saving, go back to the Vue file and no error will be reported:

Guess you like

Origin blog.csdn.net/weixin_44786530/article/details/130813178