Vue道具变成空?

时间:2017-01-30 10:23:09

标签: javascript vue.js

我的vue.js应用中有这个组件:

export default {
    props: ['forums'],

    methods: {
        increment(forum, index) {
            ForumService.increment(forum)
                .then(() => {
                    this.forums.splice(index -1, 2, this.forums[index], this.forums[index -1]);
                });
        },
    }
}

但是当我尝试增加时:

<i class="material-icons" @click="increment(forum)">&#xE316;</i>

道具forums变为空(我可以在我的vue devtools中看到)。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我无法确切地说出你在做什么,但你需要在本地复制prop,这可以在created钩子内完成,然后你可以使用本地变量而不是:

export default {
 props: ['forums'],
  created() {
    this.localForums = this.forums;  // Copy prop to local variable
  },
  methods: {
    increment(forum, index) {
      ForumService.increment(forum)
        .then(() => {
          this.localForums.splice(index - 1, 2, this.localForums[index], this.localForums[index - 1]);
        });
    },
  },
  data() {
    return {
      localForums: []
    }
  }
}

然后您可以这样调用您的方法:

<i class="material-icons" @click="increment(forum, 1)">&#xE316;</i>

我已经创建了一个JSFiddle来向您展示它是如何工作的,显然我不知道ForumService.increment(forum)做了什么(或者forum是什么),所以我只是嘲笑并返回了{ {1}}表明您没有遇到任何范围问题:

https://jsfiddle.net/wu6ad78m/

相关问题