【问题标题】:DOM is not getting updated on updating VueJS data objectDOM 在更新 VueJS 数据对象时没有得到更新
【发布时间】:2017-01-06 12:12:24
【问题描述】:

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

编辑

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

【问题讨论】:

标签: javascript vuejs2 vue.js


【解决方案1】:

首先,data 应该是一个函数并返回 {ind_case: {cmets: []}}

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

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

【讨论】:

    猜你喜欢
    • 2018-08-04
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多