使用vue.js定义全局变量的方法:首先单独新建一个全局变量模块文件,模块中定义一些变量初始状态;然后在【main.js】中引入,并通过【Vue.prototype】挂载到vue实例上面。
使用vue.js定义全局变量的方法:
原理:
1. 单独新建一个全局变量模块文件,模块中定义一些变量初始状态,用export default暴露出去。
2. 在main.js中引入,并通过Vue.prototype挂载到vue实例上面。供其他模块文件使用;
3. 或者直接引入到需要的模块文件中使用;
步骤一、定义一个全局组件 Global.vue,里面只有
步骤二、修改原型链
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import fastclick from 'fastclick'
import global_ from './components/Global.vue' //引入全局组件
Vue.prototype.GLOBAL = global_; //修改原型
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: ' '
})步骤三、使用
在需要 的vue页面直接使用 this.GLOBAL.BASE_URL,就可以获取到定义常量值