使用 vue.js 怎么定义全局变量? 下面本篇文章给大家介绍一下在 vuejs 项目中如何定义全局变量. 有一定的参考价值, 有需要的朋友可以参考一下, 希望对大家有所帮助.
一, 在需要的地方引用进全局变量模块文件, 然后通过文件里面的变量名字获取全局变量参数值.
全局变量模块 Global.JS
- const colorList = [
- 'violet',
- 'orange',
- 'blue',
- 'darkyellow',
- 'wheat',
- ]
- const colorListLength = 5
- export default
- {
- colorList,
- colorListLength
- }
模块里的变量用 export 抛出去, 当需要使用时, 引入模块 global.
- <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>
二, 在程序入口的 main.JS 文件里面, 将全局变量模块挂载到 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
四, 使用 Windows 存储变量
创建 global.JS
- const config = {
- name:'ochmd',
- age:"num"
- }
- let bindToGlobal = (obj, key) => {
- if (typeof Windows[key] === 'undefined') {
- Windows[key] = {};
- }
- for (let i in obj) {
- Windows[key][i] = obj[i]
- }
- }
- bindToGlobal(config,'_const')
在模块页面使用 Windows._const.name //ochmd
更多 web 前端开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/qa/vue-js/17218.html