Vue3_29(定義全局函數(shù)和變量)

globalProperties

由于Vue3 沒有Prototype 屬性 使用 app.config.globalProperties 代替 然后去定義變量和函數(shù)
Vue2:

Vue.prototype.$http = () => {}

Vue3:

const app = createApp({})
app.config.globalProperties.$http = () => {}

過濾器

在Vue3 移除了
我們正好可以使用全局函數(shù)代替Filters
案例:

app.config.globalProperties.$filters = {
  format<T extends any>(str: T): string {
    return `$${str}`
  }
}

聲明文件 不然TS無法正確類型 推導

type Filter = {
    format: <T extends any>(str: T) => T
}
// 聲明要擴充@vue/runtime-core包的聲明.
// 這里擴充"ComponentCustomProperties"接口, 因為他是vue3中實例的屬性的類型.
  declare module '@vue/runtime-core' {
    export interface ComponentCustomProperties {
        $filters: Filter
    }
  }

setup 讀取值

import { getCurrentInstance, ComponentInternalInstance } from 'vue';
 
const { appContext } = <ComponentInternalInstance>getCurrentInstance()
 
console.log(appContext.config.globalProperties.$env);
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 一、Vue3.0 環(huán)境搭建 使用 vite 創(chuàng)建 Vue(3.2.30)項目 npm install yarn -...
    云端釣月閱讀 585評論 0 0
  • 一、Vue2 1.1 模板語法 1.1.1 模板的理解 html 中包含了一些 JS 語法代碼,語法分為兩種,分別...
    Cola_Mr閱讀 806評論 0 1
  • Vue3的變化 官網(wǎng)地址: https://v3.cn.vuejs.org/guide/migration/int...
    JiaoMengYuan閱讀 44,008評論 0 38
  • 一些概念 Vue Composition API(VCA) 在實現(xiàn)上也其實只是把 Vue 本身就有的響應式系統(tǒng)更顯...
    前端精閱讀 7,722評論 0 23
  • vue2和vue的區(qū)別[https://mp.weixin.qq.com/s/Q2N6_ohwe0xJwesYTS...
    菜蚴菜閱讀 1,592評論 0 6

友情鏈接更多精彩內(nèi)容