我的 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)"></i>
prop forums
变为 null(我可以在我的 vue devtools 中看到这一点)。我该如何解决这个问题?
最佳答案
我无法确切地告诉你在做什么,但你需要在本地复制你的 prop
,这可以在 created
钩子(Hook)内完成,然后您可以使用局部变量来代替:
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)"></i>
我创建了一个 JSFiddle 来向您展示其工作原理,显然我不知道 ForumService.increment(forum)
的作用(或者 forum
是什么),所以我只是 mock 了它并返回了一个 promise
以表明您没有遇到任何范围问题:
关于javascript - Vue props 变成 null 了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41933523/