zoukankan      html  css  js  c++  java
  • 可用于定义全局变量的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; //

  • 相关阅读:
    域名和dns
    Oracle版本区别及版本选择!
    并发
    URL和URI的区别??
    sshpass免密码(免交互)连接
    python之路 目录
    awk sed 总结
    aiohttp使用
    Mac破解软件 “XXX”意外退出 奔溃解决方法
    我的Mac中毒了,病毒居然叫做MacPerformance
  • 原文地址:https://www.cnblogs.com/auto123-num/p/7308134.html
Copyright © 2011-2022 走看看