vue2 全域變數的設定方法,vue2全域變數
最近在學習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 = 20function 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">  <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有點繁瑣,有點殺雞用牛刀的感覺。認為並沒有必要。
以上這篇vue2 全域變數的設定方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。