Vue2.x Methods of use v-for
Introduction: It's a paper to reorganize the knowledge of List Rendering in Vue official guide. So a lot of content is from the Vue Official guide. Thanks for them.
Basic syntax
-
element-array:
<ul id="example-element-array"> <li v-for="item in items"> {{ item }} </li> </ul> -
object:
<ul id="example-object"> <li v-for="(value, name) in object"> {{ value }} - {{ name }} </li> </ul>new Vue({ el: '#example-object', data: { object: { name: 'value' } } })result:
value - name -
component
<my-component v-for="(item, index) in items" v-bind:item="item" v-bind:index="index" v-bind:key="item.id" ></my-component>recommand:
:item="item"...necessary:
:key=""
Notes
-
v-forsupports an optional second argument for the index of the current item.<ul id="example-index"> <li v-for="(item, index) in items"> {{ index }} - {{ item.message }} </li> </ul> -
use
:key=''withv-foras we can, especially list render output relies on child component state or temporary DOM state (e.g. form input values).. :key="" 根据key对item进行缓存 第二次变化时会只渲染变化的部分keyis just a identifier so it won't affecte the sort in simpleitemsthe
keyshould be unique and expectsnumber | string | boolean (since 2.4.2) | symbol (since 2.5.12)
Advanced
-
Inside
v-forblocks we have full access to parent scope properties.e.g.
<ul id="example-access-parent"> <li v-for="item in items"> {{ parentMessage }} - {{ item.message }} </li> </ul>var example2 = new Vue({ el: '#example-access-parent', data: { parentMessage: 'Parent', items: [ { message: 'msg1' }, { message: 'msg2' } ] } })result:
· Parent - msg1 · Parent - msg2 -
On the same node,
v-forhas a higher priority thanv-if.- judge if render
todeevery loop:
<li v-for="todo in todos" v-if="!todo.isComplete">{{ todo }}</li>- judge if start the entire loop:
<ul v-if="todos.length"> <li v-for="todo in todos"> {{ todo }} </li> </ul> <p v-else>No todos left!</p> - judge if render
-
use
is=""replaces<template><ul> <li is="template-todo-item" v-for="(todo, index) in todos" v-bind:key="todo.id" v-bind:title="todo.title" ></li> </ul>Vue.component('template-todo-item', { template: '\ <li>\ {{ title }}\ <button v-on:click="$emit(\'remove\')">Remove</button>\ </li>\ ', props: ['title'] })Absolute:
<li>is vaild only appear in<ul>, the opposite is the same.So uesisto indicate and replace<template>

浙公网安备 33010602011771号