Vue.js 如何从“道具”数组拼接对象,并将其分配给预定义的“数据”属性,使其具有可访问性和反应性?
我的组成部分:Vue.js 如何从“道具”数组拼接对象,并将其分配给预定义的“数据”属性,使其具有可访问性和反应性?,vue.js,vue-component,Vue.js,Vue Component,我的组成部分: props: { answerOptions: Array }, data: function() { return { selectedOption: null, //selectedOption: {}, also not working }; }, methods: { select(option, i){ //this.selectedOption = this.answerOpti
props: {
answerOptions: Array
},
data: function() {
return {
selectedOption: null,
//selectedOption: {}, also not working
};
},
methods: {
select(option, i){
//this.selectedOption = this.answerOptions.splice(i, 1); not working
//Object.assign(this.selectedOption, this.answerOptions.splice(i, 1)); also not working
this.selectedOption = Object.assign({}, this.answerOptions.splice(i, 1)); //still not
working!
console.log(this.selectedOption) //prints a observable object with alle the correct values
console.log(this.selectedOption.anyAttribute) //prints undefined
}
编辑:
这就是调用select函数的地方:
<div
ref="option-elems"
v-on:click="select(option, i)"
v-for="option, i in answerOptions"
>
answerOption数组通过for循环进行渲染。当对answerOption对象之一调用select方法时,它会将其从数组中删除,并正确更新ui中的渲染列表。我甚至可以使用selectedOption对象有条件地呈现v-if=selectedOption。但是为了上帝的爱,我无法访问它的任何属性,比如:{{selectedOption.anyAttribute}
我在这里做错了什么?您需要获取数组中名为selectedOption的对象。定义此项时,仍将对象包装在数组中,因此只需获取其第一项:
this.selectedOption = answers.splice(i, 1)[0];
你能在调用select方法的地方添加代码吗?好的,我得到了我想要的结果,不是使用splice方法返回的option对象,而是使用函数参数中的option对象。this.selectedOption=选项。但是为什么我不能使用拼接值的问题仍然存在。拼接用于数组,但您试图将其指定给对象?