更新VueJS数据对象时,DOM未获得更新

时间:2017-01-06 12:12:25

标签: javascript vuejs2 vue.js

我在JS脚本中有一个VueJS数据对象。 JS脚本链接在页面的末尾。因此,第一个HTML将被渲染。然后将初始化VueJS数据对象。初始化数据对象后,DOM将得到完美更新。但在此之后,在更新VueJS数据对象的成功函数。$ http()时,DOM没有得到更新。我已阅读有关reactivityCommon 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中获得评论。但我必须使用.comments [0] .length而不是.comments.length。这不是编码的方式。

修改

正如以下评论所示,我尝试了this。但仍然是相同的输出(即[Array[2], __ob__: Di])。还有一件事。如果我选择此选项,我必须预先定义数据对象。但我的要求是运行时创建/添加数据。

1 个答案:

答案 0 :(得分:1)

第一件事,data应该是一个函数并返回{ind_case:{comments:[]}}

我会建议您以这种方式为ajax响应创建新对象

(response) => {
  var data = response.data.map(o => getUwantProps(o));
  this.ind_case.comments = data;
}
相关问题