簡單使用vuex狀態管理的mapState和mapMutations

store.js

import Vue from ‘vue’
import Vuex from ‘vuex’

Vue.use(Vuex)

export default new Vuex.Store({
state: {
cityName:“張三”
},
mutations: {
changeStr(state,cName){
state.cityName=cName
}
},
actions: {

}
})

app.vue

{{$store.state.cityName}} // 最原始的寫法
{{cityName}}
<button @click=“btn(‘背景’)”>按鈕

import {mapState,mapMutations} from ‘vuex’
export default{
computed:{
…mapState([‘cityName’])
},
methods:{
…mapMutations([‘changeStr’]),
btn(cName){
// console.log(this.cityName)
// this.cityName=123
this.changeStr(cName)
}
}
}

使用步驟:
state ==>放入的是數據
使用數據 1.this.$store.state.cityName
2.import {mapState} from ‘vuex’
export default{
computed:mapState([‘cityName’])
}
3.computed:{…mapState([‘cityName’])}
修改數據
1.store.js
mutations: {
changeStr(state){
state.cityName=456
}
},
2.
import {mapState,mapMutations} from ‘vuex’
methods:{
…mapMutations([‘changeStr’]),
btn(){
// console.log(this.cityName)
// this.cityName=123
this.changeStr()
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章