首页 > 解决方案 > 如何从“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 }} 我在这里做错了什么?

标签: vue.jsvue-component

解决方案


您需要在名为“selectedOption”的数组中获取对象。当您定义它时,您仍然将对象包装在一个数组中,因此只需获取它的第一项:

this.selectedOption = answers.splice(i, 1)[0];

在这里演示


推荐阅读