有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤、计数等操作。
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性
一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
<!DOCTYPE html>
<html lang="en" xmlns="">
<head>
<meta charset="UTF-8">
<title>Vuex:getters 的使用</title>
</head>
<body>
<div id="app">
<button-counter></button-counter>
</div>
<script src="vuex.js"></script>
<script src="vue.js"></script>
<script>
Vue.component('ButtonCounter', {
computed: {
// 直接使用计算属性使用 getter
sellingBooks () {
return this.$store.getters.sellingBooks
},
// 使用对象展开运算符将 getter 混入 computed 对象中
...Vuex.mapGetters([
'sellingBooksCount',
'getBookById'
])
},
template: `
<div>
<h3>sellingBooks: </h3><p>{{ sellingBooks }}</p>
<h3>sellingBooksCount: </h3><p>{{ sellingBooksCount }}</p>
<h3>getBookById: </h3><p>{{ getBookById(3) }}</p>
</div>
`
})
// 创建Vuex容器
const store = new Vuex.Store({
strict: true,
state: {
books: [
{id: 1, title: 'Vue.js 从入门到秃顶', isSold: false},
{id: 2, title: 'Spring Boot 从入门到入土', isSold: true},
{id: 3, title: 'MySQL 从入门到删库跑路', isSold: true},
]
},
// 有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤、计数等操作:
// Getter 接受 state 作为其第一个参数
getters: {
// 过滤
// sellingBooks: state => { return state.books.filter(book => book.isSold === true) },
sellingBooks: state => state.books.filter(book => book.isSold === true),
// 复用 getters
// sellingBooksCount: (state, getters) => { return getters.sellingBooks.length },
sellingBooksCount: (state, getters) => getters.sellingBooks.length,
// 传值
// getBookById: (state) => (id) => { return state.books.find(book => book.id === id) }
getBookById: state => id => state.books.find(todo => todo.id === id)
},
})
new Vue({
el: '#app',
store
});
</script>
</body>
</html>