vue设置全局变量(vue2定义全局变量的3种方法)

 分类:vue教程时间:2022-06-15 07:30:32点击:

vue中怎么设置全局变量?本文是讲解在vue2中定义全局变量的3种方法,使用全局变量专用模块,挂载到main.js文件上面、全局变量模块挂载到Vue.prototype上、使用vuex定义全局变量。

vue设置全局变量

方法一:使用全局变量专用模块,挂载到main.js文件上面

1、用一个模块管理这套全局变量,模块里的变量用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
}

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

2、需要使用全局变量的模块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>

方法二:全局变量模块挂载到Vue.prototype上

1、Global.js同上,在程序入口的main.js里加下面代码

import global_ from './components/tool/Global'
Vue.prototype.GLOBAL = global_

2、挂载之后,在需要引用全局量的模块处,不需再导入全局量模块,直接用this就可以引用了,如下:

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: '主页'
 }
 ]
}
}
}

方法一和方法二的区别在于,方法二不用在用到的时候必须按需导入全局模块文件更方便,推荐此方法在vue设置全局变量

方法三:使用vuex定义全局变量

1、Vuex是一个专为Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态。因此可以存放着全局量。

// index.js文件里定义vuex
import state from './state'
export default new Vuex.Store({
  actions,
  getters,
  mutations,
  state,
})
// state.js里面存放全局变量,并且暴露出去
const state = {
  token:'12345678',
  language: 'en',
}

2、使用的时候,在需要引用全局变量的模块处直接使用this.$store调用

export default {
    methods: {
      getInternation() {
        if (this.$store.state.language === 'en') {
          this.internation = 2
        } else if (this.$store.state.language === 'zh_CN') {
          this.internation = 1
        }
      }
    } 
}
除注明外的文章,均为来源:老汤博客,转载请保留本文地址!
原文地址: