什么是vuex? 我理解的vuex就是數據和狀態的管理
如果在模塊化構建系統中,請確保在開頭調用了 Vue.use(Vuex)
五大核心:
const store = new Vuex.Store({
state: {
},
mutations: {
}
action:{
}
getter:{
}
module:{
}
})
1:state的使用:state是用來存儲數據
如何讀取數據?
讀取數據最通用的方法就是計算屬性。
computed: {
count () {
return this.$store.state.count
}
}
但是我們用map函數會簡單方便讀取數據 mapState
import { mapState } from 'vuex'
computed:{
...mapState({
// 箭頭函數可使代碼更簡練
count: state => state.count,
// 傳字符串參數 'count' 等同於 `state => state.count`
countAlias: 'count',
// 為了能夠使用 `this` 獲取局部狀態,必須使用常規函數
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
當映射的計算屬性的名稱與 state 的子節點名稱相同時,我們也可以給 mapState 傳一個字符串數組。
computed: mapState([
// 映射 this.count 為 store.state.count
'count'
])
2 mutation 這個是修改state中數據狀態的唯一方法 ,說白了就是mutation提供方法來修改state中的數據,方法中可以傳遞參數,一個是state一個是payload ,payload是調用時候單文件組件中傳遞過來的數據
如何修改提交?
mutations: {
increment (state,payload) {
// 變更狀態
state.count++
}
}
單文件組件中提交mutation中的方法
this.$store.commit('increment',{id:1})
提交increment 方法 並且傳入參數{id:1}
mapmutation提交
methods: {
...mapMutations([
'increment', // 將 `this.increment()` 映射為 `this.$store.commit('increment')`
// `mapMutations` 也支持載荷:
'incrementBy' // 將 `this.incrementBy(amount)` 映射為 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 將 `this.add()` 映射為 `this.$store.commit('increment')`
})
}