簡單筆記VueX

基本使用流程

  1. 創(chuàng)建store
import vuex from "vuex"
export.default = new vuex.Store({
    state:{
        count:0
    }
})
  1. 綁定到根視圖
vue.use(vuex)

new vue({
    store:store
})
  1. 視圖使用
    this.$store.state.count
    //一般是在conputed的計(jì)算屬性里獲取

如何修改數(shù)據(jù)呢?

  1. 使用commit來調(diào)用mutation
export.default = new vuex.Store({
    state:{
        count:0
    },
    mutations:{
        ins(state){
            state.count++
        }
    }
})


//視圖層調(diào)用
this.$store.commit('ins')

獲取變化后的state里面的數(shù)據(jù),

使用store里面的computed

getters:{
    money : ()=>`${state.count}*1000`
}

this.$store.getters.money

異步化更改數(shù)據(jù)

上面的motation是同步的,下面使用Action來異步化

actions:{
    insAsy( {commit} ){
        setTimeout(()=>{
            commit('ins'). //commit是默認(rèn)參數(shù),解析于store
        },1000)
 }
}

//視圖
this.$store.dispatch('insAsy')

dispatch傳遞參數(shù)給store

this.$store.dispatch('insAsy',{
    data:10
})


actions:{
    insAsy( store,args ){
        setTimeout(()=>{
            store.commit('ins',args)
        },1000)
 }
}

ins(state,args){
    //dosomething
}

簡化代碼

如果視圖需要更多的state數(shù)據(jù),那么我們可以這樣


import { mapState } from 'vuex'  

//計(jì)算屬性里面取出需要的
  computed: {
    ...mapState({
      sidebar: state => state.app.sidebar,
      device: state => state.app.device,
    }),
    }
    

也可以簡化Action

method:{
    ...mapActions([ins])
    ...mapMutations(['insAsy'])
}

//直接調(diào)用
this.ins()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容