当前位置 博文首页 > 超负荷小生的博客:vue--uni-app实现全局变量的三种方式

    超负荷小生的博客:vue--uni-app实现全局变量的三种方式

    作者:[db:作者] 时间:2021-09-08 19:41

    第一种:创建公共模块,需要使用变量时需要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仓库

    参考我的Vuex-Store仓库入门中第一个入门实例即可

    cs