代码之家  ›  专栏  ›  技术社区  ›  ItsPronounced Finn

使用v-for迭代json,其中id都不同,并将它们绑定到PrimeVue中的输入

  •  0
  • ItsPronounced Finn  · 技术社区  · 4 年前

    我有一个产品数据库,其中有一个名为 attributes 将属性/值对存储为JSON的。例如,我可以有一个产品,该产品将有属性,但每个产品的属性从来都不相同。因此,一种产品可能看起来像:

    #product1
    attributes {
      color: "green",
      size: "small"
    }
    

    #product2
    attributes {
      width: "12inches",
      height: "11inches
    }
    

    我正在为CRUD产品设置一个表单,包括这些动态属性。到目前为止,它看起来是这样的:

    enter image description here

    我正在使用PrimeVue创建此应用程序和表单,并尝试将这些属性/值对绑定到一些 PrimeVue components (InputText) . 它们需要使用绑定来绑定vue数据属性 v-model

    <InputText v-model="product.attribute_property" id="attribute_property" placeholder="key" />
      <span class="p-inputgroup-addon"> : </span>
    <InputText v-model="product.attribute_value" id="attribute_value" placeholder="value" />
    

    结合以下内容:

    export default {
        data() {
            return {
              product {
                
              }
          }
        }
    }
    

    解析来自数据库表的传入JSON后,它看起来是这样的(这是Vue dev tools): enter image description here

    我的计划是使用 v-for 迭代属性及其值并动态创建每个输入,但这不起作用。我知道这是因为我对这一切的运作缺乏了解。我试过:

    <div v-for="(value, key) in attributes" :key="key">
      <div class="p-inputgroup">
        <InputText v-model="key" id="attributes_key" placeholder="key" />
        <span class="p-inputgroup-addon">&nbsp;:&nbsp;</span>
        <InputText v-model="value" id="attributes_value" placeholder="value" />
      </div>
    </div>
    

    但它抱怨说 'v-model' directives cannot update the iteration variable 'key' itself . 我知道我没有正确地迭代JSON,但我不知道正确或最好的方法。这里的最终目标是将这些属性绑定到输入,并为产品创建动态属性。我只是不知道如何循环 v-for 访问属性/值对。非常感谢。

    0 回复  |  直到 4 年前
        1
  •  1
  •   user3532758    4 年前

    根据评论意见:

    如错误所述,您不能直接编辑密钥。您需要将键值对提取到一个新的对象数组中,并在编辑时引用这个新数组,并在编辑完成后重新构建产品。

    将键值对提取到新的对象数组中,

    ..
    data() {
    return {
      attributes: {
        color: "green",
        size: "small",
      },
      newAttributes: [],
     };
    },
    
    //once mounted:
    mounted: function () {
     let attributes = this.attributes;
     let keys = Object.keys(attributes);
     let newValues = [];
     keys.forEach((attrKey, i) => {
       let s = {};
       s["key"] = attributes[attrKey];
       s["val"] = attrKey;
       newValues.push(s);
     });
     this.newAttributes = newValues;
    },
    

    循环通过 newAttributes 数组,并在更新时在计算变量中重建产品数组

    computed: {
     reFormattedAttributes: function () {
       let attributes = this.newAttributes;
       let formatted = {};
       Array.from(attributes).forEach((attribute) => {
         formatted[attribute["key"]] = attribute["val"];
       });
       return formatted;
     },
    },
    
    推荐文章