1. 程式人生 > >VUE 全域性變數的幾種實現方式

VUE 全域性變數的幾種實現方式

1、全域性變數專用模組
意思是說,用一個模組(js or vue)管理這套全域性變數,模組裡的變數用export (最好匯出的格式為物件,方便在其他地方呼叫)暴露出去,當其它地方需要使用時,用import 匯入該模組

全域性變數專用模組Global.vue

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.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>
//前端全棧學習交流圈:866109386
//面向1-3經驗年前端開發人員
//幫助突破技術瓶頸,提升思維能力

1和2的區別在於:2不用在用到的時候必須按需匯入全域性模組檔案

3、vuex

Vuex是一個專為Vue.js應用程式開發的狀態管理模式。它採用集中式儲存管理應用的所有元件的狀態。因此可以存放著全域性量。因為Vuex有點繁瑣,有點殺雞用牛刀的感覺。認為並沒有必要。