VUE 全局变量的几种实现方式
来源:互联网 发布:网络打仗游戏 编辑:程序博客网 时间:2024/06/05 05:40
1、全局变量专用模块
就是以一个特定模块来组织管理这些全局量,需要引用的地方导入该模块便好。全局变量专用模块 Global.vue
const colorList = [ '#F9F900', '#6FB7B7',]const colorListLength = 20function getRandColor () { var tem = Math.round(Math.random() * colorListLength) return colorList[tem]}export default{ colorList, colorListLength, getRandColor}
模块里的变量用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>
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有点繁琐,有点杀鸡用牛刀的感觉。认为并没有必要。
作者:程序仲小仲链接:http://www.jianshu.com/p/7547ff8760c3來源:简书著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
阅读全文
0 0
- VUE 全局变量的几种实现方式
- Vue全局变量的实现方式
- vue注册组件的几种方式
- vue 传值的几种方式
- 几种全局变量的使用方法
- vue过渡效果的几种实现方法、各种滑动
- 几种声明全局变量的方式的不同以及ie中的变量人格分裂
- android传递数据的几种方式之利用全局变量进行传递
- RabbitMq的几种方式的实现
- AOP的实现的几种方式
- 实现HTTP下载的几种方式
- Singleton模式的几种实现方式
- java实现ftp的几种方式
- 几种实现身份验证的方式
- 实现打印的几种方式
- 几种下拉框的实现方式
- 实现圆角的几种方式
- Tooltip 实现的几种方式
- 强连通分量 tarjan算法 C++实现
- centos7 下的常用命令
- Android 开源交流 github [https://github.com/aosp-exchange-group/share]
- poj 2240
- 用C/C++实现较完整贪吃蛇游戏
- VUE 全局变量的几种实现方式
- Java 实现导出excel表
- Android插件框架VirtualAPK学习和使用
- java之http协议
- Snackbar的基本使用
- 8月21日云栖精选夜读:Q1财报天猫交易额增速达49%_背后有哪些新技术支撑?
- Jupyter notebook中设定py2py3同时使用
- 一语道破项目管理知识体系42个过程
- iOS 移动端生成工具开发