一、全局变量专用模块 意思是说,用一个模块(js or vue)管理这套全局变量,模块里的变量用export (最好导出的格式为对象,方便在其余地方调用)暴露出去,当其它地方须要使用时,用import 导入该模块javascript
全局变量专用模块Global.vuehtml
const colorList = [ '#F9F900', '#6FB7B7', ] const colorListLength = 20 function getRandColor () { var tem = Math.round(Math.random() * colorListLength) return colorList[tem] } export default { colorList, colorListLength, getRandColor } //前端全栈学习交流圈:866109386 //面向1-3经验年前端开发人员 //帮助突破技术瓶颈,提高思惟能力
模块里的变量用出口暴露出去,当其它地方须要使用时,引入模块全球即可。前端
须要使用全局变量的模块html5.vuevue
<template> <ul> <template v-for="item in mainList"> <div class="projectItem" :style="'box-shadow:1px 1px 10px '+ getColor()"> <router-link :to="'project/'+item.id">  <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>
二、全局变量模块挂载到Vue.prototype 里html5
Global.js同上,在程序入口的main.js里加下面代码java
import global_ from './components/tool/Global' Vue.prototype.GLOBAL = global_
挂载以后,在须要引用全局量的模块处,不需再导入全局量模块,直接用this就能够引用了,以下:vuex
<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> //前端全栈学习交流圈:866109386 //面向1-3经验年前端开发人员 //帮助突破技术瓶颈,提高思惟能力
1和2的区别在于:2不用在用到的时候必须按需导入全局模块文件dom
三、vuex学习
Vuex是一个专为Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的全部组件的状态。所以能够存放着全局量。由于Vuex有点繁琐,有点杀鸡用牛刀的感受。认为并无必要。ui