当前位置: 移动技术网 > IT编程>脚本编程>vue.js > VUE 全局变量的几种实现方式

VUE 全局变量的几种实现方式

2018年09月23日  | 移动技术网IT编程  | 我要评论

阿弥壳断层之怪,楚汉传奇若姜,网络鬼故事

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
}

模块里的变量用出口暴露出去,当其它地方需要使用时,引入模块全球便可。

需要使用全局变量的模块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的区别在于:2不用在用到的时候必须按需导入全局模块文件

3、vuex

vuex是一个专为vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态。因此可以存放着全局量。因为vuex有点繁琐,有点杀鸡用牛刀的感觉。认为并没有必要。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网