下面我就为大家分享一篇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 = 20
function 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">
<p class="projectitem" :style="'box-shadow:1px 1px 10px '+ getcolor()">
<router-link :to="'project/'+item.id">

<span>{{item.title}}</span>
</router-link>
</p>
</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有点繁琐,有点杀鸡用牛刀的感觉。认为并没有必要。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
vue的路由动态重定向和导航守卫实例
js实现为动态创建的元素添加事件操作示例
对vue里函数的调用顺序介绍
以上就是如何在vue2中设置全局变量?(详细教程)的详细内容。