vue添加全局变量

vue添加全局变量,第1张

vue添加全局变量分为3个步骤

1 建立js的util文件并输出带方法属性的对象

export default {

  // 初始化分页

  gMember() {

    console.log('gMember')

}

}

2 在main.js文件将带方法属性的对象挂载在vue中

import util from '../static/js/util.js'

Vue.prototype.$util = util

Vue3 的全局变量目前百度前面的全部是采用先

app.config.globalProperties.$axios = $axios

随后利用 getCurrentInstance 取得 ctx 或 proxy 来获取全局变量的

const { ctx } = getCurrentInstance() as any

ctx.$axios.get

但事实上官方是不建议应用使用 getCurrentInstance 方法的,

所以我更加推荐以下的方法去存储和获取全局变量,即依赖注入的方式

首先在 main.js 中

const app = createApp(App)

// 配置全局变量 页面中使用 inject 接收

app.provide('global',{

store,

axios

})

app.mount('#app')

将多个变量混同时注入的目的是为了减小依赖注册及接受的工作量

在需要接受的页面使用 inject 接受 (js项目请去掉类型声明)

<script lang="ts" setup>

import { inject } from 'vue'

// 获取全局对象`

const global:any = inject('global')

/**目前标准异步写法 */

global.axios('/harmony/getType').then((result:any) =>{

if(result.success){

list.value = result.data

}

}).catch((err:any) =>{

console.log(err)

})

</script>

采用这种方法在全局变量的创建上会更加的方便 , 而且不用担心会出现像axios在使用globalProperties设置为全局对象后丢失$axios对象只剩$http之类的问题。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11957055.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存