vue--uni-app实现全局变量的三种方式

第一种:创建公共模块,需要使用变量时需要import导入即可使用。

第一步:创建common文件和common.js

const serverUrl=www.global.com;

export default{
          
   
    serverUrl
}

第二步:在需要的vue文件中import公共模块

<template>
  <div>
    <h1>{
          
   {
          
   global_serverUrl}}</h1>
    <button @click="getGlobal()">获取全局变量</button>
  </div>
</template>
<script>
import common from ../common/common.js;
export default {
          
   
  data() {
          
   
    //这里存放数据
    return {
          
   
        global_serverUrl:""
    };
  },
  //方法集合
  methods: {
          
   
    getGlobal(){
          
   
      this.global_serverUrl = common.serverUrl;
    }
  }
};
</script>

第二种:使用Vue.prototype挂载,直接使用this调用

第一步:在main.js中进行挂载

Vue.prototype.Global_serverUrl_prototype=www.global.com;

第二步:在vue页面使用,注意:页面中不要在出现重复的属性或方法名。

<template>
  <div>
    <h1>{
          
   {
          
   global_serverUrl}}</h1>
    <button @click="getGlobal()">获取全局变量</button>
  </div>
</template>
<script>
import common from ../common/common.js;
export default {
          
   
  data() {
          
   
    //这里存放数据
    return {
          
   
        global_serverUrl:""
    };
  },
  //方法集合
  methods: {
          
   
    getGlobal(){
          
   
      this.global_serverUrl = this.Global_serverUrl_prototype;
    }
  }
};

第三种:使用vuex的store仓库

参考我的

经验分享 程序员 微信小程序 职场和发展