首页 > 解决方案 > 如何查看依赖于另一个值 vue 的值?

问题描述

首先,抱歉标题含糊;我想不出一个非常简洁的。这是我的情况:

假设我在 vuex 商店中有用户、主题和评论。用户有姓名、主题列表以及他们当前选择的主题:

users: {
  1: { 
      name: 'Tom',
      topics: [1, 2],
      selectedTopic: null // set to 1 and then 2 when user clicks "next"
    },
  2: {... }
},
topics:
  1: { 
      title: 'Post!',
      comments: [1, 2],
      selectedComment: null
    },
  2: { ... }
},
comments:
  1: { 
      title: 'Cool!'
    },
  2: { ... }
}

如果选择了一个用户,我想显示他们的名字。如果用户还选择了一个主题,该主题也应该显示出来;他们还可以循环浏览主题。对于每个主题,他们可以以相同的方式循环浏览评论。因此:

computed: {
  // some getters
  // ...
  user () {
    return this.getUser(this.userId)
  },
  topic () {
    return this.getTopic(this.user.topics[this.user.selectedTopic])
  },
  comment () {
    return this.getComment(this.topic.comments(this.topic.selectedComment])
  }

在这种情况下,循环工作,但控制台显示TypeError: "this.user.topics is undefined""this.user.selectedTopicis undefined"在开始时(仅有时),这是真的,当然,因为我们尚未选择用户。另一方面,如果我将其替换为

  topic () {
    if (this.user) return this.getTopic(this.user.topics[this.user.selectedTopic])
  }

我没有收到任何错误,但是当所选主题发生更改时,值也不会更新。有什么好的方法来处理这个问题吗?

标签: vue.jsvuejs2vue-componentvuexcomputed-properties

解决方案


根据Ivo Gelov的评论,我到达了

return this.getTopic((this.user.topics || {})[this.user.selectedTopic])

这似乎可以解决问题。


推荐阅读