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之类的问题。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)