vue基础(11)--vuex通用

112 阅读1分钟

------------------------------------简化基本用法示例--------------------------------------

import Vuex from 'vuex'
import Vue form 'vue'

Vue.use(Vuex)

export default ()=>{
    return  new Vuex.Store({   
        state:{
            count:0
        },
        mutations:{
            updateCount(state,num){
                state.count = num
            }
        }
    })
}

使用index.js

import createStore form './store.js'

const store= createStore()

应用里面
mounted(){
    console.log(this.$store)
    this.$store.commit('updateCount',10)
},
computed(){
    count(){
        return this.$store.state.count
    }
}

-----------------------------------------项目用法-----------------------------------------
  1. store.js存储
  2. mutation.js修改
  3. actions.js修改
  4. getters获取
  5. state数据定义初始化

state.js

export default{
    count:0,
    firstName:'liu',
    lastName:'liu'
}

mutation.js

export default {
    updateCount(state,num){
        state.count = num
    }
}

action.js                         //异步修改数据,多次调用mutation修改

export default {
    updateCountAsync(state,data){
        setTimeout(()=>{
            store.commit('updateCount',{
                num:data.num
            })
        },data.time)
    }
}

getters.js 数据组装作用较多

export default {
    fullName(state){
         return `${state.firstName} ${state.lastName}`
    }
}

store.js 

export default()=>{
    return new Vuex.Store({
        state:defaultState,
        mutations,
        getters,
        actions
    })
}


------------------------------------------用法示例-----------------------------------------

 app.vue

mounted(){    
    this.$store.dispatch('updateCountAsync',{  //aciton对应方法
        num:5,
        time:200
    })
}
computed:{    fullName(){
        return this.$router.getters.fullName
    }
}

语法糖

import {mapState,mapGetters,mapActions,mapMutations} from 'vuex'

computed:{ 
    ...mapState({
        counter:'count' //(state)=>{state.count+1}
    }),
    ...mapGetters(['fullName'])
},
methods:{
    ...mapActions(['updateCountAsync]),
    ...mapMutations(['updateCount'])
}

坑: 不支持es6的语法 ...   

修理方法: .babelrc文件加入,完事

{
  "presets": [
    "env",
    "stage-1"        //加入这货
  ]
}