其他分享
首页 > 其他分享> > vuex基础用法

vuex基础用法

作者:互联网

state 存放全局数据
this.$store.state.***
this.$store.commit('addFn',参数)
this.$store.dispath('addAsync',参数)
修改 state数据需要调用 
state:{
    **:''
}
mutation中不能处理一步操作
mutation:{
    addFn(state,(参数)){
        state.** -= 参数
    }
}
组件调用
import {mapState,mapMutations,mapActions } form 'vuex'
// 计算属性存放state 值
computed:{
    ...mapState(['state内值'])
}
methods:{
    ...mapMutations([
        'mutation中定义的函数(addFn)
    ])
     ...mapMutations({
      add: 'addFn' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
}
组件函调用mutation 传入函数
 fatherClick(){
     store.commit('addFn')
    // store.commit('add')
 }

 

当处理值发生异步则需要调用 action

actions:{
    // 在actions中,不能直接修改 state 中数据
    // 必须通过 context.commit() 触发某个 mutation才行
    addAsync(context){
      发送的请求
      setTimeout(()=>{
        context.commit('addFn')
      },1000)
    }
}
组件调用函数
fatherClick(){
    // dispatch 函数,专门触发 action
    第一中调用方法
    this.$store.dispatch('addAsync')
}
第二种调用方法 
methods:{
    ...mapActions(['addAsync'])
}
fatherClick(){
    this.addAsync()
    // 可以直接写在按钮事件上 @click=“addAsync”
}

标签:基础,用法,state,addFn,mutation,commit,addAsync,vuex,store
来源: https://www.cnblogs.com/yugueilou/p/15957231.html