Vuex 工作错误

Vuex working wrong

我的 vuex 看起来像:

state: {
  loadedUsers: [
    { id: 10, classId: 1, name: 'X' },
    { id: 11, classId: 1, name: 'Y' },
    { id: 13, classId: 2, name: 'Z' }
  ]
}
getters: {
  loadedUsers (state) {
    return (classId) => {
      return state.loadedUsers.find((user) => {
        return user.classId === classId
      })
    }
  }
}

和我计算的:

computed: {
  users () {
    return this.$store.getters.loadedUsers(1)
  }
}

它只是 returns { id: 10, classId: 1, name: 'X' }

当我使用 like

时也是如此
this.$store.getters.loadedUsers(this.$route.params.classid)

classid 到达但 returns 为空

可能是什么问题?

那是因为 Array.prototype.find() returns the value of the first element that matches. You should be using Array.prototype.filter() 而不是。此外,您可以通过一层展开 function/method 调用:

getters: {
  loadedUsers (state) {
    return classId => state.loadedUsers.filter((user) => {
      return user.classId === classId
    })
  }
}