在下面的VueJS 2组件中,我可以将imgdata属性添加到area.questions数组中的每个问题。它有效-从console.log中可以看到imgdata具有值的问题。但是,尽管使用了$ set,它仍然没有响应,并且imgdata在视图中不存在!我该如何使它具有反应性?
var componentOptions = {
props: ['area'],
data: function() {
return {
qIndex: 0,
};
},
mounted: function() {
var that = this;
that.init();
},
methods: {
init: function() {
var that = this;
if (that.area.questions.length > 0) {
that.area.questions.forEach(function(q) {
Util.HTTP('GET', '/api/v1/photos/' + q.id + '/qimage').then(function(response) {
var thisIndex = (that.area.questions.findIndex(entry => entry.id === q.id));
var thisQuestion = (that.area.questions.find(entry => entry.id === q.id));
thisQuestion.imgdata = response.data;
that.$set(that.area.questions, thisIndex, thisQuestion);
})
});
}
console.log("area.questions", that.area.questions);
},
答案 0 :(得分:2)
由于area
是一个道具,因此您不应尝试在此组件中对其进行更改。
通常的想法是为父组件发出一个事件以监听以更新传入的数据。
例如
export default {
name: "ImageLoader",
props: {
area: Object
},
data: () => ({ qIndex: 0 }), // are you actually using this?
mounted () {
this.init()
},
methods: {
async init () {
const questions = await Promise.all(this.area.questions.map(async q => {
const res = await Util.HTTP("GET", `/api/v1/photos/${encodeURIComponent(q.id)}/qimage`)
return {
...q,
imgdata: res.data
}
}))
this.$emit("loaded", questions)
}
}
}
在父母中
<image-loader :area="area" @loaded="updateAreaQuestions"/>
export default {
data: () => ({
area: {
questions: [/* questions go here */]
}
}),
methods: {
updateAreaQuestions(questions) {
this.area.questions = questions
}
}
}
答案 1 :(得分:-1)
此处,变量的值为this,但受函数范围限制。因此,您可以在数据中创建反应性属性,如下所示:
data: function() {
return {
qIndex: 0,
questions: []
};
}
that。$ set(this.questions,thisIndex,thisQuestion);
并使用this.questions将您的API输出直接分配给问题。