• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

vue3定义全局函数和变量

武飞扬头像
派小鑫
帮助1

vue2是用Vue.prototype 属性来定义的全局函数和变量,但vue3是没有这个属性的。vue3可以通过app.config.globalProperties 来定义

一、定义属性

  1.  
    // main.ts中
  2.  
    app.config.globalProperties.$evn= '挂载全局属性'
  3.  
     
  4.  
    console.log(app.config.globalProperties,'app.config.globalProperties')

运行截图:

学新通

 二、定义函数

  1.  
    // main.ts
  2.  
    type Filter = {
  3.  
    format<T>(str: T): string
  4.  
    }
  5.  
     
  6.  
    app.config.globalProperties.$filters = {
  7.  
    format<T extends any>(str: T): string {
  8.  
    return `'添加过滤'${str}`
  9.  
    }
  10.  
    }
  11.  
     
  12.  
    declare module 'vue' {
  13.  
    export interface ComponentCustomProperties {
  14.  
    $filters: Filter
  15.  
    }
  16.  
    }
学新通

vue项目文件:

  1.  
    <template>
  2.  
    <div>{{appContext.config.globalProperties.$filters.format(dispalay)}}</div>
  3.  
    </template>
  4.  
     
  5.  
    <script lang="ts" setup>
  6.  
    import { reactive, ref, onMounted ,getCurrentInstance, ComponentInternalInstance } from 'vue'
  7.  
    const { appContext } = <ComponentInternalInstance>getCurrentInstance()
  8.  
     
  9.  
    const dispalay = ref('小明')
  10.  
    console.log(appContext.config.globalProperties.$evn);
  11.  
     
  12.  
    </script>

页面显示:

学新通

  1.  
    // 第二种使用方式
  2.  
    import { reactive, ref, onMounted ,getCurrentInstance } from 'vue'
  3.  
     
  4.  
    const app = getCurrentInstance()
  5.  
    console.log(app?.proxy?.$filters.format('js'))
  6.  
     
  7.  
    // 控制台打印
  8.  
    '添加过滤'js

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgghgia
系列文章
更多 icon
同类精品
更多 icon
继续加载