欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

VUE 全局變量的幾種實現(xiàn)方式

 更新時間:2018年08月22日 10:07:13   作者:夏有喬木  
這篇文章主要介紹了VUE 全局變量的幾種實現(xiàn)方式,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

1、全局變量專用模塊

意思是說,用一個模塊(js or vue)管理這套全局變量,模塊里的變量用export (最好導出的格式為對象,方便在其他地方調(diào)用)暴露出去,當其它地方需要使用時,用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
}

模塊里的變量用出口暴露出去,當其它地方需要使用時,引入模塊全球便可。

需要使用全局變量的模塊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>

1和2的區(qū)別在于:2不用在用到的時候必須按需導入全局模塊文件

3、vuex

Vuex是一個專為Vue.js應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài)。因此可以存放著全局量。因為Vuex有點繁瑣,有點殺雞用牛刀的感覺。認為并沒有必要。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論