VUE 全局变量的几种实现方式

最近在学习VUE.js 中间涉及到JS全局变量,与其说是VUE的全局变量,不如说是模块化JS开发的全局变量。

1、全局变量专用模块

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

全局变量专用模块 Global.vue
<script type="text/javascript">
const colorList = [
  '#F9F900',
  '#6FB7B7',
  '#9999CC',
  '#B766AD',
  '#B87070',
  '#FF8F59',
  '#FFAF60',
  '#FFDC35',
  '#FFFF37',
  '#B7FF4A',
  '#28FF28',
  '#1AFD9C',
  '#00FFFF',
  '#2894FF',
  '#6A6AFF',
  '#BE77FF',
  '#FF77FF',
  '#FF79BC',
  '#FF2D2D',
  '#ADADAD'
]
const colorListLength = 20
function getRandColor () {
  var tem = Math.round(Math.random() * colorListLength)
  return colorList[tem]
}
export default
{
  colorList,
  colorListLength,
  getRandColor
}
</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>
3、使用VUEX

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态。因此可以存放着全局量。因Vuex有点繁琐,有点杀鸡用牛刀的感觉。认为并没有必要。
链接:vuex官方介绍

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 有了你之后 走在路上 也会莫名拉起唇角 有了你之后 在喜欢的旋律里想着喜欢的你 大汗漓淋 一个人也觉得好开心 对了...
    庄洁淳阅读 1,755评论 0 2
  • 02 2 03-钟艳 今天我们一起来学习绘本的《文图合奏的力量》,我们先来了解一下作家李欧.李奥尼的人生经历,他出...
    小黏糊艳子阅读 1,267评论 0 0
  • 第一次发文章
    bin你阅读 962评论 0 0
  • 六年级学习任务重压力大的时候,孩子对妈妈说:“我觉得上学好辛苦啊,能不能不上学了?” 妈妈回答说:“可以啊!如果现...
    wins希儿阅读 1,404评论 0 0