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

How to define global variables using vue.js

coldplay.xixi
Release: 2023-01-13 00:44:58
Original
6294 people have browsed it

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>
Copy after login

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;
})
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template