在此只讲在main.js文件中新增全局变量的方法,不讨论在App.vue中定义globalData全局对象的方法。
main.js中定义全局变量:
假如我们需要定义名称为baseUrl的全局变量:
vue2方法:(通过Vue.prototype)
Vue.prototype.$baseUrl = 'http://www.mkkkk12222m.work'
vue3方法:(通过app.config.globalProperties)
app.config.globalProperties.$baseUrl = 'http://12.mkkkk12222m.work'
下边贴出一个main.js的代码供参考看下定义方法和语句所在的位置:
// #ifndef VUE3
import Vue from 'vue'
import App from './App'
import store from './store'
Vue.config.productionTip = false
App.mpType = 'app'
Vue.prototype.$baseUrl = 'http://12.mkkkk12222m.work'
Vue.prototype.$store = store
const app = new Vue({
store,
...App
})
app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
import App from './App.vue'
import store from './store'
export function createApp() {
const app = createSSRApp(App)
app.use(store)
app.config.globalProperties.$baseUrl = 'http://12.mkkkk12222m.work'
return {
app
}
}
// #endif
定义之后如何在单文件组件页面里使用呢,很简单,直接this.$变量名 即可,例如我们例子里定义的baseUrl,直接用this.$baseUrl即可调用。如下:
//index.vue
...
<script>
export default {
data() {
return {
}
},
onLoad() {
console.log(this.$baseUrl)
},
methods: {
}
}
</script>