I have a VueJS data object in JS script. The JS script is linked at end of the page. So first HTML will is getting rendered. Then VueJS data object will be initialised. After initialising data object, DOM is getting updated perfectly. But after this, on updating the VueJS data object in success function of this.$http(), DOM is not getting updated. I have read documentation on reactivity and Common Beginner Gotchas. But I didn't get solution. If anyone knows the answer, it will be appreciated.
Here is my code.
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) => {})
}
}
....
})
As seen in code, I can get comments in DOM. But I have to use .comments[0].length instead of .comments.length. And that's not the way to code.
EDIT
As suggested in below comment, I have tried this. But still same output (i.e, [Array[2], __ob__: Di]
). And also one more thing. If I choose this option, I have to pre-define data object. But my requirement is run time creation/addition of data.
.comments.length
works. What's your.comments.length
? – PanJunjie潘俊杰 Jan 10 at 9:24