一、全局變量專用模塊 意思是說,用一個模塊(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