vue.js - 如何从“props”数组中拼接一个对象并将其分配给预定义的“data”属性,使其可访问和反应?
问题描述
我的组件:
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
}
编辑:这就是调用选择函数的地方:
<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];
推荐阅读
- python - 为什么在尝试使用 int 函数时出现此错误
- vb.net - 您可以像在 VB6 中一样“静态”使用 VB.Net 表单吗?
- php - 如何在 Laravel 5.8 API 中生成 GET 请求 Swagger API Doc?
- python - 提取单引号正则表达式和python之间的短语
- flutter - 根据是新登录用户还是返回用户在 Flutter 中导航屏幕
- python - Mpmath findroot 用于多维函数错误“无法从矩阵创建 mpf”
- r - 在数据框列上使用 poly
- c# - C# EF 一对多可选关系
- git - Git-Visual Studio 2019 中的本地分支签出不会恢复分支工作区
- javascript - 为什么我的数据库属性在 IndexDB 中不断重置?