【问题标题】:How Key and value Iterate in Vue JsVue Js 中的 Key 和 value 如何迭代
【发布时间】:2021-02-16 21:20:32
【问题描述】:

我正在尝试使用 vue.js 中的键和值迭代波纹管数组。

attributes = {"Size - UK":"12","Color":"White"}.

这个array 正在从数据库中获取string

我想要如下结果

Size : 12 Color : White

我使用下面的方法来做到这一点

 <span :v-for="(item, index) in attributes">
     {{item}} : {{index}}
 </span>

我遇到了这样的错误。

Property or method "index" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property

我该如何解决这个问题?

【问题讨论】:

    标签: loops vue.js for-loop vue-component v-for


    【解决方案1】:

    v-for 属性不应包含:(请参阅docs

    删除: 试试这个:

    // https://codepen.io/collection/naevzw/
    var example1 = new Vue({
      el: '#example-1',
      data: {
        items:
          { message: 'Foo', text: 'Bar', other: 'FooBar' }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <!-- v-for - VUE.js Guide Example -->
    <ul id="example-1">
      <li v-for="(key) in Object.keys(items)">
        {{ key }} : {{ items[key] }}
      </li>
    </ul>

    【讨论】:

    • 我试过了。但我得到这样的结果 '0 : { 1 :" 2 : S 3 : i 4 : z 5 : e 6 : 7 : - 8 : 9 : U 10 : K 11 :" 12 : : 13 :" 14:1 15:2 16:“17:,18:”19:C 20:o 21:l 22:o 23:r 24:“25::26:”27:W 28:h 29:i 30: t 31:e 32:“33:}”
    • 我从数据库中以string 获取此数组,这是个问题吗?
    • 问题是我的数组是字符串我添加JSON.parse(items) to.problem 是固定的。谢谢大家
    【解决方案2】:

    试试这个:

    <span v-for="key in Object.keys(attributes)">
         {{key}} : {{attributes[key]}}
     </span>
    

    【讨论】:

    • 这不起作用。获取错误称为TypeError: Cannot use 'in' operator to search for 'undefined' in {"Size - UK":"12","Color":"White"}
    • 我试过了。但我得到这样的结果 '0 : { 1 :" 2 : S 3 : i 4 : z 5 : e 6 : 7 : - 8 : 9 : U 10 : K 11 :" 12 : : 13 :" 14:1 15:2 16:“17:,18:”19:C 20:o 21:l 22:o 23:r 24:“25::26:”27:W 28:h 29:i 30: t 31:e 32:“33:}”
    • 问题是我的数组是字符串我添加JSON.parse(attributes) to.problem 是固定的。谢谢大家
    猜你喜欢
    • 2020-01-25
    • 1970-01-01
    • 2016-01-11
    • 2021-08-05
    • 1970-01-01
    • 2015-10-12
    • 2017-02-01
    • 2011-05-16
    • 1970-01-01
    相关资源
    最近更新 更多