我一直很难避免Vuex模块中的 "结巴"。只是似乎大多数时候,模块的名字也就是它所包含的内容。
例如,假设一个处理用户的模块。我把这个模块文件命名为 user.js
export default {
state: {
users: []
},
// mutations and actions for reading, creating, updating users...
}
然后在我店里的 index.js
import user from 'user';
export default new Vuex.Store({
modules: {
user
}
});
当我想从一个组件中获取用户列表时,我必须使用。
this.$store.user.users
如果我不使用模块来获取用户列表,我就只能用... this.$store.users
这就更容易读懂和优雅了。
有什么办法可以避免这种结巴的命名惯例或设计模式吗?
你可以使用 mapState
.
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
users: state => state.user.users
})
// ...
}
然后你可以使用 this.users
别名 this.$store.user.users