如何观察取决于另一个值vue的值?

时间:2020-05-27 16:55:35

标签: vue.js vuejs2 vue-component vuex computed-properties

首先,对标题含糊不清表示抱歉;我无法提出一个非常简洁的建议。这是我的情况:

假设我在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])
  }

我没有收到任何错误,但是更改所选主题时值也不会更新。有解决这个问题的好方法吗?

1 个答案:

答案 0 :(得分:0)

基于commentIvo Gelov,我到达了

bool

这似乎可以解决问题。