vuex的使用

vuex是什么

vuex是一个专门为vue开发的状态管理工具,它采用集中式存储管理应用的所有组件的状态,其核心是state。

vuex内容

        state:存放状态数据的地方,其中数据是响应式的,数据改变对应组件的数据也会跟新改变,禁止直接改变state中的数据否则数据无法被调试工具监测。
        getter:可理解为store的计算属性,能读取state中的数据。
        mutations:(同步)装着处理数据逻辑方法的集合体,是该改变state中数据的唯一方法,修改数据是同步的。
        actions:(异步)提交mutations修改数据,与mutations功能类似,但修改数据是异步的,可以包含任意异步操作。

const store = new Vuex.Store({
    state:{
        count:0;
        },
    mutations:{
        increment(state){
            state.count++
        }
    },
    action:{
        increment(context){
            context.commit('increment')
        }
    }
})


        modules:当store过于臃肿时,可使用modules将store分割成模块,每个模块中都有自己的state、getter、mutations、actions

在使用页面

放在computed里的内容有(state、getter)

放在methods里的内容有(mutation、action)

view
<p>{{getTodoById(2).text}}</p>
<button @click="asyncIncrement">点我</button>

store
mutations:{
    increment(state,{num=1}){
        //mutation提交会立即形成一条改变记录
        state.count+=num
    },
    [SOME_MUTATION](state){ 
    //专门设置mutations文件存放常量,有助于多人能够很快知道页面有哪些mutation
        state.message = 'hello'
    }
},
actions:{
    increment({commit},{num = 1}){
        setTimeout(function(){
            commit({
                type:'increment',
                num
             })
         },1000)
    }
},
getters:{
    remaining:state=>{
        return state.todos.filter(item=>item.done===false).length
    },
    getTodoById:state=>{
        return id=>{
            return state.todos.find(item=>item.id === id)
        }
    }
})


script的export default中
methods:{
    //不建议在组件中直接修改容器中的数据,因为无法被调试工具记录到
    increment(){
        this.$store.commit({
            type:'increment',
            num:2
        })
    },
    asyncIncrement(){
        this.$store.dispatch('increment',{
        num:2
        })
    },
    ...mapAction(['asyncIncrement'])
    ...mapMutations(['COME_MUTATION'])

computed:{
    count(){
        return this.$store.state.count
    }
    ...mapState({
        count:'count',
        message:'message',
    })
    ...mapGetters(['remaining','getTodoById'])
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值