Home  >  Article  >  Web Front-end  >  How to define global variables using vue.js

How to define global variables using vue.js

coldplay.xixi
coldplay.xixiOriginal
2020-12-24 14:34:316239browse

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.

How to define global variables using vue.js

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&gt ;

<!--设置全局变量-->
<script>
    //接口地址
    const BASE_URL = &#39;http://118.189.105.152:7181/qianzhang-transf/index/&#39;; //定义全局接口地址
    //请求头部       
    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 &#39;vue&#39;
import App from &#39;./App&#39;
import router from &#39;./router&#39;
import fastclick from &#39;fastclick&#39;
import global_ from &#39;./components/Global.vue&#39;  //引入全局组件
Vue.prototype.GLOBAL = global_;  //修改原型
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
  el: &#39;#app&#39;,  
  router, 
  components: { App },
  template: &#39;<App/>&#39;
})

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn