【问题标题】:How can I nest v-fors inside my component file?如何在我的组件文件中嵌套 v-fors?
【发布时间】:2016-10-14 12:36:30
【问题描述】:

我已经阅读了 VueJS 教程,但我仍然无法提出解决方案。

我有一个列表列表,我想使用手风琴显示它们(这是 vue-strap 的一个组件,之前经过多次测试可以正常工作)。

所以有一个列表,例如:

'myList': [
  ['el 1', 'el 2', 'el 3'], ['el 1', 'el 2'], ['el another']
]

我希望得到以下可视化效果:

清单 1:

  • el 1
  • el 2
  • el 3

清单 2:

  • el 1
  • el 2

清单 3:

  • 另一个

但是 VueJS 没有渲染这个组件...!

代码如下:

<template>
  <accordion id="rabo" :one-at-atime="true">
    <template v-for="list in myLists">
      <panel header="List #{{ $index }}" :is-open="true">
        <ul>
          <li v-for="el in list">
            {{el}}
          </li>
        </ul>
      </panel>
    </template>
  </accordion>
</template>

<style lang="scss" scoped>
</style>

<script>
  import Vue from 'vue'
  import { accordion, panel } from 'vue-strap'

  module.exports = {
    components: {
      'accordion': accordion,
      'panel': panel
    }
  }

  new Vue({
    el: '#rabo',
    data: {
      'myLists': [['el 1', 'el 2', 'el 3'],['el 1','el 2'],['el another']]
    }
  })
</script>

【问题讨论】:

  • 另一个&lt;template&gt; 标签内的&lt;template&gt; 标签对我来说看起来不合适。您应该定义第二个组件,然后在您的第一个模板中使用该组件。但是,以您为例,您可能只想删除第二个 &lt;template&gt; 标记并替换为另一个元素,例如 div 。另外,你在使用 Vueify 吗?

标签: javascript vue.js vue-component


【解决方案1】:

你应该:

  1. 将 Vue 实例创建到单独的文件中
  2. myLists数组放入组件的data
  3. 绑定header属性

MyAccordion.vue

<template>
  <accordion :one-at-atime="true">
    <template v-for="list in myLists">
      <panel :header="`List #${$index}`" :is-open="true">
        <ul>
          <li v-for="el in list">
            {{el}}
          </li>
        </ul>
      </panel>
    </template>
  </accordion>
</template>

<script>
  import { accordion, panel } from 'vue-strap'

  export default {
    components: {
      accordion, panel
    },

    data () {
      return {
        myLists: [
          ['el 1', 'el 2', 'el 3'],
          ['el 1', 'el 2'],
          ['el another']
        ]
      }
    }
  }
</script>

Vue 实例

import Vue from 'vue'
import MyAccordion from './MyAccordion.vue'

new Vue({
  el: '#demo',
  components: { MyAccordion }
})

http://www.webpackbin.com/VyPHjF_V-

【讨论】:

  • 太棒了!你能告诉我 $index 变量有什么问题吗? VueJS 没有处理它,它在网页中显示 ${$index}。我尝试了所有我能记住的 ${{$index}}、${{index}}、${index} 等组合...谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-01-07
  • 2017-12-31
  • 2020-03-12
  • 2019-06-04
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
相关资源
最近更新 更多