Vue3使用全局函数或变量的两种常用方式

02-27 阅读 0评论

例如:想要在index.ts中创建getAction函数,并可以全局使用

Vue3使用全局函数或变量的两种常用方式,Vue3使用全局函数或变量的两种常用方式,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,使用,创建,第1张
(图片来源网络,侵删)
import { http } from '@/utils/axios'
export function getAction (url: string, params: object) {
  return http.request({
    url: url,
    method: 'get',
    params: params
  })
}

方式一:使用依赖注入(provide/inject)

在main.ts中进行挂载:

import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
import { getAction } from 'index'
app.provide('getAction', getAction) // 将getAction方法挂载到全局
app.mount('#app')

在要使用的页面注入:

import { inject } from 'vue'
const getAction: any = inject('getAction')

方式二:使用 app.config.globalProperties 和 getCurrentInstance()

  • app.config.globalProperties:一个用于注册能够被应用内所有组件实例访问到的全局属性的对象
  • getCurrentInstance():// 获取当前实例,类似于vue2的this
    import { createApp } from 'vue'
    import App from './App.vue'
    const app = createApp(App)
    import { getAction } from 'index'
    app.config.globalProperties.$getAction = getAction
    app.mount('#app')

     在要使用的页面中使用:

    import { getCurrentInstance } from 'vue'
    const { proxy }: any = getCurrentInstance()
    console.log('proxy:', proxy)
    console.log('getAction:', proxy.$getAction)
    
    Vue3使用全局函数或变量的两种常用方式,Vue3使用全局函数或变量的两种常用方式,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,使用,创建,第2张
    (图片来源网络,侵删)
    Vue3使用全局函数或变量的两种常用方式,Vue3使用全局函数或变量的两种常用方式,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,使用,创建,第3张
    (图片来源网络,侵删)

免责声明
本网站所收集的部分公开资料来源于AI生成和互联网,转载的目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

发表评论

快捷回复: 表情:
评论列表 (暂无评论,人围观)

还没有评论,来说两句吧...

目录[+]