
Vue3 的全局变量目前百度前面的全部是采用先
appconfigglobalProperties$axios = $axios
随后利用 getCurrentInstance 取得 ctx 或 proxy 来获取全局变量的
const { ctx } = getCurrentInstance() as any
ctx$axiosget
但事实上官方是不建议应用使用 getCurrentInstance 方法的,
所以我更加推荐以下的方法去存储和获取全局变量,即依赖注入的方式
首先在 mainjs 中
const app = createApp(App)
// 配置全局变量 页面中使用 inject 接收
appprovide('global',{
store,
axios
})
appmount('#app')
将多个变量混同时注入的目的是为了减小依赖注册及接受的工作量
在需要接受的页面使用 inject 接受 (js项目请去掉类型声明)
<script lang="ts" setup>
import { inject } from 'vue';
// 获取全局对象`
const global:any = inject('global')
/目前标准异步写法 /
globalaxios('/harmony/getType')then((result:any) => {
if(resultsuccess){
listvalue = resultdata
}
})catch((err:any) => {
consolelog(err);
});
</script>
采用这种方法在全局变量的创建上会更加的方便 , 而且不用担心会出现像axios在使用globalProperties设置为全局对象后丢失$axios对象只剩$>
如果在Vue中有多个页面都需要使用同一个方法 getSemester,有多种方式可以处理,以下是其中一些常见的方法:
在每个页面中分别定义 getSemester 方法,这种方法比较简单,但代码冗余度较高。
在单独的文件中定义 getSemester 方法,并在每个页面中引入该文件,这种方法可以减少冗余代码,但是需要在每个页面中引入文件,不太方便。
将 getSemester 方法定义为全局方法或Vue实例方法,这样就可以在任何Vue组件中使用。在Vue中,可以使用Vuemixin或Vueprototype扩展全局方法或实例方法。
使用Vuemixin扩展全局方法:
// 在mainjs中定义
Vuemixin({
methods: {
getSemester() {
// 方法实现
}
}
})
// 在mainjs中定义
VueprototypegetSemester = function() {
// 方法实现
}
eg:
原本路由:
>
let a = documentgetElementById('phone_input')
afocus() //需要手动聚焦一下
consolelog(avalue)
thisvalue14 = avalue
consolelog(thisvalue14)
以上就是关于vue3如何配置getapp()这样的全局变量全部的内容,包括:vue3如何配置getapp()这样的全局变量、vue在ios上getDay() 为NAN的问题 (日期转星期)解决、vue4个页面用到同一个方法getsemester,你会如何处理等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)