1、全局变量专用模块

就是以一个特定模块来组织管理这些全局量,需要引用的地方导入该模块便好。
全局变量专用模块 Global.vue

<script>
    const QueryApplyInfo = {};
    const AreaInfoList = {};
    const OrderDictList = {};
    const decodeOrderDict = {}
    const ProfessionInfoList = {};
    const decodeProfessionInfo = {};
    export default {
        QueryApplyInfo,
        AreaInfoList,
        OrderDictList,
        decodeOrderDict,
        ProfessionInfoList,
        decodeProfessionInfo
    }
</script>

模块里的变量用export 暴露出去,当其它地方需要使用时,引入模块global便可。

需要使用全局变量的模块 html5.vue

<template>
  <ul>
    <template v-for="item in mainList">
      <div class="projectItem" :style="'box-shadow:1px 1px 10px '+ getColor()">
          <router-link :to="'project/'+item.id">
            ![](item.img)
            <span>{{item.title}}</span>
          </router-link>
      </div>
    </template>
  </ul>
</template>
<script type="text/javascript">
import global_ from 'components/tool/Global'
export default {
  data () {
    return {
      getColor: global_.getRandColor,
      mainList: [
        {
          id: 1,
          img: require('../../assets/rankIcon.png'),
          title: '登录界面'
        },
        {
          id: 2,
          img: require('../../assets/rankIndex.png'),
          title: '主页'
        }
      ]
    }
  }
}
</script>
<style scoped type="text/css">
.projectItem
{
  margin: 5px;
  width: 200px;
  height: 120px;
  /*border:1px soild;*/
  box-shadow: 1px 1px 10px;
}
.projectItem a
{
  min-width: 200px;
}
.projectItem a span
{
  text-align: center;
  display: block;
}
</style>

2、全局变量模块挂载到Vue.prototype 里。

Global.js同上,在程序入口的main.js里加下面代码

import global_ from './components/tool/Global'
Vue.prototype.GLOBAL = global_

挂载之后,在需要引用全局量的模块处,不需再导入全局量模块,直接用this就可以引用了,如下:

<script type="text/javascript">
export default {
  data () {
    return {
      getColor: this.GLOBAL.getRandColor,
      mainList: [
        {
          id: 1,
          img: require('../../assets/rankIcon.png'),
          title: '登录界面'
        },
        {
          id: 2,
          img: require('../../assets/rankIndex.png'),
          title: '主页'
        }
      ]
    }
  }
}
</script>

或者基于组件

// xxx.js 组件
exports.install = function (Vue, options) {
    Vue.prototype.ajax = function (){
        alert('aaaaaaa');
    };
};

// main.js 入口
import xxxx from './commons/xxxx'
Vue.use(xxxx);

// ccc.js 子组件
this.ajax();

3、使用VUEX
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态。因此可以存放着全局量。因Vuex有点繁琐,有点杀鸡用牛刀的感觉。

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'

Vue.use(Vuex)
const store = new Vuex.Store({
    state, //定义变量
    mutations
})

export default store 

然后在 XXX.vue 子组件中使用方法
方法一 在子组件引入store利用store.state.count 来调用

import store from "@/store"
store.state.count 

方法二 无需引入 由于路由store已经在new Vue() 注册,所以也可以直接使用this.$store.state来调用

this.$store.state //调用方法

版权声明:本文为李维亮博主的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:http://www.liweiliang.com/890.html

标签: none

评论已关闭