v-if, v-else, v-else-if, v-show
v-if
is used to determine if an element will be rendered. It is used in conjuction with v-else
and v-else-if
to chain conditionals and determine the rendering of multiple elements.
<div v-if="type === 'A'"> A </div> <div v-else-if="type === 'B'"> B </div> <div v-else-if="type === 'C'"> C </div> <div v-else> Not A/B/C </div>
v-if
can be used with the <template>
tag to determine the renderization of multiple elements at once.
<template v-if="ok"> <h1>Title</h1> <p>Paragraph 1</p> <p>Paragraph 2</p> </template>
v-show
is also used to determine if an element will be rendered or not. The difference with v-if
is that v-show
use the css property display
to show or not an element, while v-if
removes or adds the element from the DOM.
<h1 v-show="ok">Hello!</h1>
v-for
v-for
is used for rendering elements in a list. It is possible to render elements from an array but also from an object, and even ranges. The :key
attribute is used for helping Vue keep a good update performance when the list is mutated.
const items = ref([ { id: 'foo', message: 'Foo', show: true }, { id: 'bar', message: 'Bar', show: true }, { id: 'baz', message: 'Baz', show: false } ]) const myObject = reactive({ title: 'How to do lists in Vue', author: 'Jane Doe', publishedAt: '2016-04-10' })
<!-- <li v-for="(item, index) of items"> is also valid --> <ul> <li v-for="(item, index) in items" :key="item.id"> {{ item.message }} </li> </ul> <!-- It is possible to loop over object properties --> <ul> <li v-for="(value, key, index) in myObject"> {{ index }}. {{ key }}: {{ value }} </li> </ul> <!-- Use in ranges --> <span v-for="n in 10">{{ n }}</span> <!-- If used v-for and v-if is recommended to use v-for on <template> and v-if in children --> <template v-for="item in items" :key="item.id"> <li v-if="item.show"> {{ todo.name }} </li> </template> <!-- v-for can be used also on components --> <MyComponent v-for="(item, index) in items" :item="item" :index="index" :key="item.id" />
References