【发布时间】:2021-07-19 16:50:45
【问题描述】:
就清洁逻辑和维护而言,以下场景的最佳做法是什么?
我的用例是有一个查询对象,它的参数是一堆text和之前查询的结果。
我最初认为代码结构如下(见伪代码):
data() {
return {
queries : {
q1 : { data: `${this.text} + ${this.formerResults}` }
// q2, q3...
},
formerResults : ''
}
},
methods : {
makeQuery : function() {
let vm = this;
axios({ /* param of the query, data : this.queries.q1 */ })
.then((response) => { vm.formerResults += /* add the results */ })
}
这个问题是formerResults 确实被附加了,但在下一个查询q1 中注入时结果为undefined。我不知道为什么,但通过将查询 q1 构造为计算属性解决了这个问题。
您能说出为什么在使用属性时逻辑会失败,并且可以使用计算属性吗?
computed: {
q1() {
return {
// same as above
}
}
// q2, q3 ...
}
并在我的方法中调用它:
axios({ /* param of the query, data : this.q1 */ });
可以看到text和formerResults这两个参数都通过了。
但是,我想将查询(q1、q2、q3..)分组在同一个对象 queries 下,就像在 data() 中一样:这是为了代码清晰,因为所有这些查询都是针对相同的url,我可能还有其他的。
但是尝试:
computed: {
computedQueries : {
q1() {
return {
// same as above
}
},
// q2, q3 ...
}
}
并在我的方法中这样称呼它:
axios({ /* param of the query, data : this.computedQueries.q1 */ })
会导致vue报错:
Error in v-on handler: "TypeError: Cannot read property 'q1' of undefined"
您能否说明如何将计算属性分组(或嵌套)到一个对象中?
我是否真的需要在我的示例中使用计算属性,以避免在下一个查询中未定义 formerResults?你能建议如何保持代码干净吗?
【问题讨论】:
标签: vue.js methods readability maintenance computed-properties