vue.js - 如何查看依赖于另一个值 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])
}
我没有收到任何错误,但是当所选主题发生更改时,值也不会更新。有什么好的方法来处理这个问题吗?
解决方案
根据Ivo Gelov的评论,我到达了
return this.getTopic((this.user.topics || {})[this.user.selectedTopic])
这似乎可以解决问题。
推荐阅读
- python - 运行电报机器人
- gradle - Gradle:如何只允许特定的传递依赖
- mysql - mysqld 消耗 232% CPU
- macos - 如何连接 NSTableView/Table View 以避免运行时错误“无法连接操作,目标类 NSObject 不响应”)
- android - 在 Green Dao 注释实体中使用 Embedded POJO 类
- android - 如何判断android设备分辨率是小、中还是大
- python - ImportError:无法导入名称“SubgradientStructuredSVM”
- javascript - 为什么不能在 javascript 中获得正确的日期(加上 1 天)?
- java - Java 将 .xls 文件显示为 .xls 和 xlsx 的两倍
- android - 上传文件时出现错误(没有这样的文件或目录)