一、Vuex與Vue.mapState介紹
在大型Vue.js應用程序中,使用組件進行狀態管理是相當棘手的。在每個組件中都會有一些數據需要共享以及可預測的修改規則。為了解決這個問題,Vue.js提供了Vuex狀態管理庫。Vuex 將狀態和操作分開管理,狀態更新是通過提交「mutations」的方式,而不是直接修改。Vue.js 還提供了一個輔助函數 Vue.mapState,它是一個可以用來將 store 中的 state 映射到局部計算屬性中的實用程序函數。
下面我們來看一個簡單的使用示例,這裡假設我們有一個store,保存著當前的用戶名:
const store = new Vuex.Store({
state: {
username: 'Alice'
}
})
現在我們想在 Vue 組件中使用該狀態,在組件計算屬性中使用 Vue.mapState:
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
username: state => state.username
})
}
}
現在組件的計算屬性具有了狀態的副本:
console.log(this.username) // -> "Alice"
二、使用Vue.mapState獲取多個狀態
在Vue.mapState中我們可以獲取並映射多個狀態,示例如下:
computed: {
...mapState({
doubleCount: state => state.count * 2,
username: state => state.username
})
}
這裡使用了一個計算屬性doubleCount映射state中count的兩倍,還將username狀態映射為組件中的用戶名變數。
三、使用Vue.mapState獲取嵌套狀態
如果你的狀態比較複雜,可能會包含嵌套對象,例如這樣:
const store = new Vuex.Store({
state: {
user: {
name: 'Alice',
age: 27
}
}
})
此時我們就需要使用Vue.mapState的更高級用法:傳遞一個數組,其中第一個元素是需要映射到組件計算屬性的值的鍵
computed: {
...mapState([
'username',
'user' // 映射 this.user 為 store.state.user
])
}
現在,組件的計算屬性具有以下副本:
console.log(this.user) // -> { name: 'Alice', age: 27 }
console.log(this.username) // -> 'Alice'
四、使用Vue.mapState與Vuex的輔助函數
除了Vue.mapState以外,Vuex還提供了一些輔助函數來簡化代碼。例如:全局輔助函數mapState、mapGetters、mapActions和mapMutations。
下面我們來使用全局輔助函數mapState獲取state中的count:
import { mapState } from 'vuex'
export default {
computed: {
...mapState([
'count'
])
}
}
這段代碼等同於:
computed: {
count () {
return this.$store.state.count
}
}
這樣,我們就可以不需要使用Vuex的store實例,而直接在組件中獲取state中的count。
五、總結
Vuex 狀態管理和 Vue.mapState 都是 Vue.js 相當重要的部分。在Vue.js開發中,我們都會涉及到組件狀態管理。這時我們可以使用Vuex進行全局狀態管理,在組件中使用Vue.mapState獲取這些狀態。使用輔助函數也是很方便的,通過這些函數能夠幫助我們簡化代碼,提高開發效率。在Vue.js中同時使用Vuex和Vue.mapState是成為一名優秀的Vue開發者的標誌之一。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/195596.html