美文网首页
vue vuex状态管理

vue vuex状态管理

作者: 星星藏进黑夜 | 来源:发表于2019-03-11 23:30 被阅读0次

    一、安装

        cnpm i vuex --save-dev
    

    二、引入(main.js)

        import store from './store'
    
        new Vue({
              el: '#app',
              router,
              store,//注册
              components: { App },
              template: '<App/>'
        })
    

    三、vuex配置 src > store > index.js(src下创建store目录,目录中创建index.js)

    
    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    let state = {
            box1: '0',
            box2: '1'
    }
    let getters = {
            getbox1(state){
                    return state.box1
            },
             getbox2(state){
                    return state.box2
            }
    }
    let mutations = {
            setBox1(state, str){
                    state.box1 += str
            }, 
             setBox2(state, str){
                    state.box2 += str
            }
    }
    let actions = {
            acBox1(context, str){
                    context.commit('setBox1', str)
            },
            acBox2(context, str){
                    context.commit('setBox2', str)
            }
    }
    let store = new Vuex.Store({
            state, getters, mutations, actions
    })
    export default store; // 导出配置项
    

    四、组件中使用

    this.$store.state.box1  // 获取state变量
    this.$store.getters.getbox1  // 获取getter变量
    this.$store.dispatch('acBox1', '1')  // 调用actions的方法
    this.$store.commit('setBox1', '1')  // 调用mutations的方法
    

    相关文章

      网友评论

          本文标题:vue vuex状态管理

          本文链接:https://www.haomeiwen.com/subject/thcapqtx.html