• 可用于定义全局变量的vuex,及vuex用法


    1. vuex文件index.js

       文件内容:

       import Vue from 'vue'

       import Vuex from 'vuex'

       Vue.use(Vuex)

    const store = new Vuex.Store({

         state: {

             flag: true

         },

         mutations: {},

         actions: {},

         modules: {}

    })

    export default store

    然后,在main.js文件中的

    首先引入上述文件 import store from './store/index.js'(或者import store from './store'这样写,一般会自动去找这个文件夹下的index.js文件),

    在下面的位置加入代码:

    const app = new Vue({

        router: router,

        render: h => h(App),

       store: store  // 添加上这一行的代码

    })

    这样,就可以在项目中的其他页面中调用这个vuex文件中的变量或方法了。

    例如格式: console.log(this.$store.state.flag) // true

    this.$store.state.flag = false; // 或者修改变量值,可以达到不同页面之间的传递数值

    2.在vuex中使用module形式:

    还是以上述代码为基础

    vuex文件index.js

       文件内容:

       import Vue from 'vue'

       import Vuex from 'vuex'

       Vue.use(Vuex)

     // 自定义module

    import toolBox from './toolBox.js'  // import 后跟的名字为自定义的,可以是任何自己习惯使用的名称

    const store = new Vuex.Store({

         state: {

             flag: true

         },

         mutations: {},

         actions: {},

         modules: {

            toolBox: toolBox  // 冒号之前的toolBox为自定义的名称,供在项目的其他页面调用使用;冒号之后的toolBox为上面import时的自定义名称,意在映射。 

        }

    })

    export default store

    在main.js文件中的引用同上,在main.js文件中的

    首先引入上述文件 import store from './store/index.js'(或者import store from './store'这样写,一般会自动去找这个文件夹下的index.js文件),

    在下面的位置加入代码:

    const app = new Vue({

        router: router,

        render: h => h(App),

       store: store  // 添加上这一行的代码

    })

    那么toolBox.js里面如何设置呢?其实格式和index.js的格式一模一样的!!!

    这样,就可以在项目中的其他页面中调用的时候就是这样:

    例如格式: console.log(this.$store.state.toolBox.flag) // true

    this.$store.state.toolBox.flag = false; //

  • 相关阅读:
    KMP算法小结
    算法二叉搜索树之AVL树
    算法导论之红黑树的学习
    算法导论小结(一)
    感悟或摘抄
    js中神奇的东西
    简单了解webservice
    用<![CDATA[]]>将xml转义为 纯文本
    简单了解soap协议
    java写webservice接口
  • 原文地址:https://www.cnblogs.com/auto123-num/p/7308134.html
Copyright © 2020-2023  润新知