首页 > 解决方案 > Vuejs 从数组创建列表

问题描述

我在使用 Vuejs 创建列表时遇到了一个奇怪的问题。我有一个像这样的数组:

const sr = new Vue({
  el: '#singlerecipe-app',
  data: {
    checkeditems: [],
  },
});

这是在我的 HTML 中实例化的,如下所示:

<div class="container" id="singlerecipe-app">
  <singlerecipe :checkeditems="checkeditems"></singlerecipe>
</div>

并在我的组件中声明为 Prop:

Vue.component('singlerecipe', {
  props: ['checkeditems'],
  template: `
    <ul>
       <li v-for="item of checkeditems">
           {{ item.checkeditems }}
       </li>
    </ul>
  `
})

检查项目代码为:

<li v-if="result.strIngredient1">
    <input type="checkbox" :value="result.strIngredient1" :id="result.strIngredient1" v-model="checkeditems"> {{result.strIngredient1}} - {{result.strMeasure1}}
</li>
<li v-if="result.strIngredient2">
    <input type="checkbox" :value="result.strIngredient2" :id="result.strIngredient2" v-model="checkeditems"> {{result.strIngredient2}} - {{result.strMeasure2}}
</li>

如果我单击其中一个复选框,它肯定会向数组 checkeditems[] 添加正确的值,但奇怪的是,它会创建新的列表项但不会添加值,所以我最终得到了这个:

<ul>
  <li></li>
  <li></li>
</ul>

列表项中没有值。有谁知道我做错了什么?

标签: arraysvue.js

解决方案


我想你只是不小心添加了一个“checkeditems”。

它应该是:

Vue.component('singlerecipe', {
  props: ['checkeditems'],
  template: `
    <ul>
       <li v-for="item of checkeditems">
           {{ item }}
       </li>
    </ul>
  `
})

推荐阅读