美文网首页
vue基础 matution、state、action

vue基础 matution、state、action

作者: 幻影翔 | 来源:发表于2019-12-09 07:40 被阅读0次

matution

 import vue from 'vue'
 const mutations = {
   // state 同级的state
  SET_APP_NAME (state,params) {
      state.appName = params
  },
  SET_APP_VERSION (state) {
    vue.set(state,'appVersion','v2.0')
  },
  SET_STATE_VALUE (state,val) {
    state.stateValue = val
  }
 }
 export default mutations

state

const state = {
appName: 'admin',
stateValue: 'abc'
}
export default state

action

 import { getAppName } from '@/api/app'
 const actions = {
 async updateAppName ({ commit }) {
    try {
        const { info: { appName } } = await getAppName()
        commit('SEt_APP_NAME',appName)
    } catch (err) {
        console.log(err)
    }
  }
}
export default actions

使用

import {mapState, mapGetters,mapMutations,mapActions} from 'vuex'
computed: {
    appName () {
        return this.$store.state.appName
    },

    appNameWithVersion () {
        return this.$store.getters.appNameWithVersion
    },
    ...mapGetters([
        'firstLetter'
    ]),
    ...mapState({
        userName: state => state.user.userName,
        appVersion: state => state.appVeVrsion,
        todoList: state => state.user.todo ? state.user.todo.todoList : [],
    }),
    stateValue: {
        get () {
            return this.$store.state.stateValue
        },
        set (value) {
                this.SET_STATE_VALUE(value)
        }
    }
},
methods: {
    ...mapMutations ([
        'SET_APP_NAME',
        'SET_USER_NAME',
        'SET_STATE_VALUE'
    ]),
    ...mapActions([
        'updateAppName'
    ]),
    handleChangeAppName () {
        // 提交的函数名称,新的值
        //this.$store.commit('SET_APP_NAME','MyAppName'),
        this.SET_APP_NAME('jackson006')
        //this.updateAppName('')
        //this.$store.commit('SET_APP_VERSION')
    },
    handleChangeUserName () {
        this.SET_USER_NAME('你好')
        //this.$store.dispatch('updateAppName','123')
    },
    registerModule () {
        this.$store.registerModule(['user','todo'], {
            state: {
                todoList: [
                    '学习mutations',
                    '学习actions'
                ]
            }
        })
    },
    handleStateValueChange (value) {
        this.SET_STATE_VALUE(value)
    }
  }
}

相关文章

网友评论

      本文标题:vue基础 matution、state、action

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