VUE.js 中涉及到JS全局变量
一、全局变量专用模块得引入
全局变量模块 Global.js
const colorList = [
 'violet',
 'orange',
 'blue',
 'darkyellow',
 'wheat',
]
const colorListLength = 5
export default
{
 colorList,
 colorListLength
}
模块里的变量用export 抛出去,当需要使用时,引入模块global。
需要使用全局变量的模块 html.vue
<template>
 <ul>
  <template v-for="item in mainList">
  <div v-for="item in getColor" :key="item">
   {{item}}
  </div>
  </template>
 </ul>
</template>
<script type="text/javascript">
import global_ from './components/Global'
export default {
 data () {
  return {
   getColor: global_.colorList
  }
 }
}
</script>
二、全局变量模块挂载到Vue.prototype 。
Global.js同上,在main.js里加下面代码
import global_info from './components/Global' Vue.prototype.GLOBAL = global_info
挂载之后,在需要引用全局量的模块处,不需再导入全局量模块,直接用this就可以,如下:
<script type="text/javascript">
export default {
 data () {
  return {
   getColor: this.GLOBAL.colorList
  }
 }
}
</script>
三、使用VUEX存储状态值
Vuex是一个专门为Vue.js应用程序开发的状态治理模式, 它接纳集中式存储治理所有组件的公共状态, 并以响应的规则保证状态以一种可展望的方式发生变化.
store.js界说
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
// 建立vuex的store
export default new Vuex.Store({
  state: {
    count: 1
  },
  // 更改store的状态
  mutations: {
    increment(state) {
      state.count++;
    },
    decrement(state) {
      state.count--;
    }
  },
  // 有异步的时刻, 需要action
  actions: {
    increment(context) {
      context.commit("increment");
    },
    decrement(context) {
      setTimeout(function() {
        context.commit("decrement");
      }, 10);
    }
  },
  // 通过getter 举行数据获取
  getters: {
    getState(state) {
      return state.count > 0 ? state.count : 0;
    }
  }
});
在main.js,引入store.js
import store from "./store/index";
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");
在页面模块直接使用store挪用
count=this.$store.state.count
四、使用window存储变量
建立 global.js
const config = {
    name:'ochmd',
    age:"num"
}
let bindToGlobal = (obj, key) => {
     if (typeof window[key] === 'undefined') {
         window[key] = {};
     }
     for (let i in obj) {
         window[key][i] = obj[i]
     }
}
bindToGlobal(config,'_const')
在模块页面使用window._const.name //ochmd
1.阿里云: 本站现在使用的是阿里云主机,平安/可靠/稳固。点击领取2000米代金券、领会最新阿里云产物的种种优惠流动点击进入
2.腾讯云: 提供云服务器、云数据库、云存储、视频与CDN、域名等服务。腾讯云各种产物的最新流动,优惠券领取点击进入
3.广告同盟: 整理了现在主流的广告同盟平台,若是你有流量,可以作为参考选择适合你的平台点击进入
链接: http://www.fly63.com/article/detial/3572