【发布时间】:2017-01-06 12:12:24
【问题描述】:
我在 JS 脚本中有一个 VueJS 数据对象。 JS 脚本链接在页面末尾。所以第一个 HTML 将被渲染。然后 VueJS 数据对象将被初始化。初始化数据对象后,DOM 得到完美更新。但是在此之后,在 this.$http() 的成功函数中更新 VueJS 数据对象时,DOM 没有得到更新。我已阅读有关 reactivity 和 Common Beginner Gotchas 的文档。但我没有得到解决方案。如果有人知道答案,将不胜感激。
这是我的代码。
index.html
<body>
....
{{ind_case.comments.length}}
<div class="comment_item" v-for="comment in ind_case.comments">
</div>
....
<script src="index.js"></script>
</body>
index.js
new Vue({
....
data: {
ind_case: {}
},
created: function () {
this.getCaseDetails();
},
methods: {
getCaseDetails: function () {
this.ind_case = {
"case_id": 16
}
this.getCaseComments(this.ind_case.case_id);
},
getCaseComments: function(case_id){
this.$http.get('/api/comments/' + case_id)
.then((response) => {
console.log(response.data); // Output: [{cmnt: "blah"}, {cmnt: "blah blah"}]
// Here i want add these comments in ind_case data object as ind_case.comments
// I have tried this
// this.$set(this.ind_case, 'comments', response.data);
// console.log(this.ind_case.comments); // Output: [Array[2], __ob__: Di]
}, (response) => {})
}
}
....
})
从代码中可以看出,我可以在 DOM 中获取 cmets。但我必须使用 .cmets[0].length 而不是 .cmets.length。这不是编码的方式。
编辑
正如下面评论中所建议的,我已经尝试过this。但仍然是相同的输出(即[Array[2], __ob__: Di])。还有一件事。如果我选择这个选项,我必须预先定义数据对象。但我的要求是运行时创建/添加数据。
【问题讨论】:
-
我已经对此进行了测试,一切正常,
.comments.length有效。你的.comments.length是什么? -
您解决了这个问题吗?我通过简单地推送到数组和正确更新 DOM 完成了同样的事情。
标签: javascript vuejs2 vue.js