【问题标题】:Cannot render list using V-for in VueJs无法在 VueJs 中使用 V-for 渲染列表
【发布时间】:2020-08-05 07:38:50
【问题描述】:

我是 Vue 的新手,我正在尝试遍历一个数组。不完全知道我做错了什么,但列表没有显示在 HTML 上。下面是代码: 这是一个通过路由器视图呈现的索引文件。

<template>
  <div class="index container">
    <div class="card" v-for="tournament in tournaments" :key="tournament.id">
      <div class="card-content">
        <h2 class="indigo-text">{{tournament.title}}</h2>
        <ul class="tournaments">
          <li v-for="(score,index) in tournamnet.scores" :key="index"></li>
          <span class="chip">{{score}}</span>
        </ul>
      </div>
    </div>
    
  </div>
</template>

<script>
export default {
  name: 'index',
  data () {
    return {
     tournaments:[
       {title:'Muthaiga golf Tournament',slug: 'muthaiga-golf-tournament',scores:['Round 1', 'Round 2', 'Round 3'],id:'1'},
       {title:'Wilson Churchhill',slug: 'Wilson Churchhill',scores:['Round 1', 'Round 2', 'Round 3'],id:'2'},
       ]
    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>

</style>

这里是路由器视图 index.js

import Vue from 'vue'
import Router from 'vue-router'
import index from '@/components/index'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'index',
      component: index
    }
  ]
})

这里是 app.vue

<template>
  <div id="app">
   <navbar />
    <router-view/>
  </div>
</template>

<script>
import navbar from '@/components/navbar'
export default {
  name: 'App',
  components:{
    navbar
  }
}
</script>

我们将不胜感激。

【问题讨论】:

  • 你看到了什么?你看到你的navbar了吗? &lt;div class="index container"&gt; 呢?究竟是什么没有按预期工作?
  • 这能回答你的问题吗? Correct way to handle v-if with v-for in Vue
  • 我可以看到我的导航栏,但我看不到
  • 你确定这不是因为你写的错字tournamnet.scores 而不是tournament.scores

标签: vue.js


【解决方案1】:

将您的跨度放在v-for

<ul class="tournaments">
  <li v-for="(score,index) in tournament.scores" :key="index+'tournament'">
    <span class="chip">{{score}}</span>
  </li>
</ul>

另外,最好不要使用索引作为键,我添加了字符串'tournament' 使其更加独特。

此外,请确保您已更正“锦标赛”的拼写。


Link to official docs.

【讨论】:

  • index 作为key 有什么问题?仅供参考,我同意使用数组索引作为键通常不是一个好主意(特别是如果数组已排序),但它没有任何问题,并且不需要使它们更独特跨度>
  • 哦,这只是为了避免出现问题,以防万一他在组件中的某个地方有另一个以索引为键的 v-for。有时它还会在控制台中发出警告,具体取决于设置。
  • 您的观点很好,但在这种情况下,您最好重命名 index 变量本身
【解决方案2】:

您在&lt;li v-for="(score,index) in tournamnet.scores" :key="index"&gt;&lt;/li&gt; 上有错字

拼错比赛

如果您查看控制台,您应该会看到

vue.runtime.esm.js?2b0e:619 [Vue warn]: Property or method "score" 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. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

found in

---> <Index> at src/components/index.vue
       <App> at src/App.vue
         <Root>

【讨论】:

  • 非常感谢,错字是问题所在。我现在可以看到我的头衔,但看不到分数。让我再筛选一遍,看看我是否还有另一个让我痛苦的错字。
猜你喜欢
相关资源
最近更新 更多
热门标签