用什么命名来避免Vuex模块中的 "结巴"?

问题描述 投票:2回答:1

我一直很难避免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这就更容易读懂和优雅了。

有什么办法可以避免这种结巴的命名惯例或设计模式吗?

javascript vue.js vuex
1个回答
1
投票

你可以使用 mapState.

import { mapState } from 'vuex'


export default {
  // ...
  computed: mapState({
    users: state => state.user.users
  })
  // ...
}

然后你可以使用 this.users 别名 this.$store.user.users

© www.soinside.com 2019 - 2024. All rights reserved.