前几天在跟着视频做项目中发现,人家是用的Vue2的框架,而我敲的是Vue3的,人家的全局变量引用我没法使用,所以一度困扰了我很长时间,后来查阅了很多资料,发现基本上在Vue3中并不推荐使用全局变量,最后还是找到了方法使用。

首先在main.js中写好全局属性:

Vue3中的定义方法是:app.config.globalProperties.[名称]=属性

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
//请求基准路径配置[即后台地址]
axios.defaults.baseURL='http://127.0.0.1:8080/api/'
const app = createApp(App)
app.config.globalProperties.$axios = axios

//将全局的echarts对象挂载到vue的原型对象上
app.config.globalProperties.$echarts = window.echarts
app.use(store).use(router).mount('#app')

 定义好后在想要应用的组件的脚本标签下先引入getCurrentInstance方法:

import { getCurrentInstance } from "vue"

然后在export default  下的  setup() 生命周期中获取全局属性,这里有两种调用方法,任选其一,我选择使用第一种方法。


    setup() {
        //全局调用方法1
        const { proxy } = getCurrentInstance();
        //console.log(proxy)
        //console.log(proxy.$axios)
        return { proxy }

        //全局调用方法2
        // const instence = getCurrentInstance()
        // const ins = instence.appContext.config.globalProperties
        //console.log(ins.$axios,typeof(ins.$axios))
    },

注意在生命周期中要return{  }返回获取到的信息,不然无法在其他方法中使用。

之后在该组件的其他生命周期及方法中调用使用this. 即可,例如echarts和 axios:

initChart() {
    this.chartInstance = markRaw(this.$echarts.init(this.$refs.trend_ref, this.theme))
}

async getData(ret) {
    const {data: ret} = await this.$axios.get('trend')
    console.log(ret)
    this.allData = ret
}

 

 

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐