Home >Web Front-end >Vue.js >How to define global variables using vue.js
How to use vue.js to define global variables: First, create a separate global variable module file, and define some initial states of variables in the module; then introduce it in [main.js] and pass it through [Vue.prototype] Mounted to the vue instance.
The operating environment of this tutorial: Windows 7 system, Vue version 2.9.6, DELL G3 computer.
【Recommended related articles: vue.js】
How to use vue.js to define global variables:
Principle:
1. Create a new global variable module file separately, define some initial states of variables in the module, and use export default to expose them.
2. Introduce it in main.js and mount it to the vue instance through Vue.prototype
. For use by other module files;
3. Or directly introduced into the required module file for use;
Step 1. Define a global component Global.vue, which only contains <script> ;
<!--设置全局变量--> <script> //接口地址 const BASE_URL = 'http://118.189.105.152:7181/qianzhang-transf/index/'; //定义全局接口地址 //请求头部 const reqHead = { "transDate": "20180816", "encryptFlag": "1", "seqNo": "2018081628507127", "serviceID": "loanLmtQryHXMKL", "transTime": "174341", "channelID": "netbank" } export default { //将常量暴露出去 BASE_URL, reqHead, } </script>
Step 2. Modify the prototype chain
// 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: '<App/>' })
Step 3. Use
directly on the required vue pagethis.GLOBAL.BASE_URL
, you can get the defined constant value
Related free learning recommendations:javascript(Video)
The above is the detailed content of How to define global variables using vue.js. For more information, please follow other related articles on the PHP Chinese website!