vue2 全域變數的設定方法,vue2全域變數

來源:互聯網
上載者:User

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">      ![](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><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 全域變數的設定方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.