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

来源:互联网 发布:网络打仗游戏 编辑:程序博客网 时间:2024/06/05 05:40

1、全局变量专用模块

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

const colorList = [  '#F9F900',  '#6FB7B7',]const colorListLength = 20function getRandColor () {  var tem = Math.round(Math.random() * colorListLength)  return colorList[tem]}export default{  colorList,  colorListLength,  getRandColor}

模块里的变量用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>

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有点繁琐,有点杀鸡用牛刀的感觉。认为并没有必要。

作者:程序仲小仲链接:http://www.jianshu.com/p/7547ff8760c3來源:简书著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。