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)
}
}
}
网友评论