【问题标题】:How to watch for a value which depends on another value vue?如何查看依赖于另一个值 vue 的值?
【发布时间】:2020-09-14 19:36:06
【问题描述】:

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

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

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: { ... }
}

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

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])
  }

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

【问题讨论】:

  • 您可以使用保护措施 - return this.getTopic(((this.user || {}).topics || {})[(this.user || {}).selectedTopic || ''])
  • @IVOGELOV 谢谢 - 但这无济于事,我仍然得到(intermediate value).topics is undefined...
  • 应该 topic() computed 是:topic () { if (this.user) return this.getTopic(this.user.selectedTopic) } 吗?
  • 当您期望某个值是 undefinednull - 您应该附加 || default 以便表达式将评估为给定的默认值(您将根据情况选择此默认值- 例如,它可能是一个空数组或空对象或 0 或空字符串 ....)。您应该为您希望有时为 undefined 的任何值提供默认值。
  • 您的版本实际上是我第一次回复的略微简化/剥离的版本 :) 很高兴看到您理解这个想法!

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


【解决方案1】:

基于Ivo Gelovcomment,我到达了

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

这似乎可以解决问题。

【讨论】:

    猜你喜欢
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 2017-01-05
    • 1970-01-01
    • 2015-07-13
    • 2020-10-19
    • 1970-01-01
    相关资源
    最近更新 更多