【问题标题】:VueJS nested list rendering with propsVueJS 使用 props 渲染嵌套列表
【发布时间】:2017-04-27 21:46:55
【问题描述】:

我想用 Vue.js 渲染一个嵌套列表,但我的代码在嵌套组件部分失败。 我的主要模板:

<body>
  <div id="app">
    <ul>
      <li v-for="todo in todos">
        {{ todo.text }}
        <ul>
          <todo-item v-for="subtodo in todo.subTodos" v-bind:subtodo="subtodo"></todo-item>
        </ul>
      </li>
    </ul>
  </div>
</body>

还有我的js文件:

Vue.component('todo-item', {
  template: '<li>{{subtodo.text}}</li>',
  prop: ['subtodo']
})

var app = new Vue({
  el: '#app',
  data: function () {
    return {
      todos : [
        { 
          text : 'Learn JavaScript', 
          subTodos : [
            { text : 'Linting'}, 
            { text : 'Bundling'}, 
            { text : 'Testing'}
          ]
        },
        { 
          text : 'Learn Vue', 
          subTodos : [
            { text : 'Components'}, 
            { text : 'Virtual DOM'}, 
            { text : 'Templating'}
          ]
        },
        { 
          text : 'Build something awesome', 
          subTodos : [
            { text : 'Build'}, 
            { text : 'Something'}, 
            { text : 'Awesome'}
          ]
        }
      ]
    }
  }
})

基本上在第一级,我使用v-for 渲染一个数组,然后我将一个实例传递给子组件以进行另一次迭代,我还将v-bind 传递给当前实例,以便我可以在子模板中使用它。

我在这里有一个工作小提琴:https://jsfiddle.net/ny7a5a3y/4/

控制台给了我这个错误:

[Vue warn]: Property or method "subtodo" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

我错过了什么?

【问题讨论】:

  • 它的错字道具是正确的不是道具

标签: vue.js vue-component vuejs2


【解决方案1】:

打错了,你说的组件中的 prop 正确的是 props

Vue.component('todo-item', {
  template: '<li>{{subtodo.text}}</li>',
  props: ['subtodo']
})

https://jsfiddle.net/uofmd96q/

【讨论】:

    【解决方案2】:

    试试这个:

    <todo-item v-for="st of todo.subTodos" :subtodo="st"></todo-item>
    

    【讨论】:

      【解决方案3】:

      如果有人需要在单击时呈现嵌套列表,以供将来参考,这是我使用项目索引制作的一个非常简单的嵌套列表示例。

      <div v-for="(aggList, index) in aggregationList">
              <div v-on:click="LoadAggIndex(index)">
                  {{aggList.name}} and index: {{index}}
              </div>
      
          </div>
      
      <div v-for="agg in loadedAggList">
              {{agg.key}}
              {{agg.count}}
          </div>
      

      Vue.js

       methods: {
              LoadAggIndex: function (index) {
                  SearchBar.loadedAggList = SearchBar.aggregationList[index].aggregates;
              }
          }
      

      【讨论】: