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-for
supports 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-for
as we can, especially list render output relies on child component state or temporary DOM state (e.g. form input values)..key
is just a identifier so it won‘t affecte the sort in simpleitems
the
key
should be unique and expectsnumber | string | boolean (since 2.4.2) | symbol (since 2.5.12)
Advanced
-
Inside
v-for
blocks 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-for
has a higher priority thanv-if
.- judge if render
tode
every 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 uesis
to indicate and replace<template>