Inside a template, you can add special attributes that convey meaning to Vue. They are called directives.
Directives start with v-
, to indicate that’s a Vue special attribute.
For example:
<a v-bind:href="url">{{ linkText }}</a>
<span v-text="name"></span>
<p v-if="shouldShowThis">Hey!</p>
There are lots of directives, which we’ll see later. Now I want to focus the attention on v-for
.
v-for
allows you to render a list of items. Say you have a list of items. You can render it using:
<template>
<ul>
<li v-for="item in items">{{ item }}</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: ['car', 'bike', 'dog']
}
}
}
</script>
Cool!
Here’s another example of displaying a list, this time using an array of objects:
<template>
<div>
<ul>
<li v-for="todo in todos">{{ todo.title }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
todos: [
{ id: 1, title: 'Do something' },
{ id: 2, title: 'Do something else' }
]
}
}
}
</script>
v-for
can give you the index using:
<li v-for="(todo, index) in todos"></li>