You can determine which part of the template to display depending on the value of data properties. Vue provides directives v-if
, v-else-if
and v-else
to select what HTML content to show. The excerpt from example p304.html displays different message based on the value of temperature
and rain
.
<div id="app">
<div>Temperature: {{ temperature }}°C
<span v-if="temperature>=25">It's hot!</span>
<span v-else-if="temperature>=10">pleasant weather</span>
<span v-else>It's cold, stay warm</span>
</div>
<div>Rain: {{ rain }}%
<img v-if="parseFloat(rain)>=30" src='image/umbrella.png'>
</div>
</div>
<script>
const weather = {
data() {
return { temperature: 28, rain: 10 }
}
};
const vm = Vue.createApp(weather).mount('#app');
</script>
Refer to the online reference for more detail of v-if
and other conditional rendering directives.
When you want to display a list of content, you often group the content in an array in the data property, and use the directive v-for
to repeat some HTML code for each item in the list. The example p305.html below shows an array of string values using a sequence of <span>
elements.
<div id="app">
<p v-if="sport.length===0">I don't really like sports</p>
<p v-else>My favorite sports:
<span v-for='x in sport' class='box'>{{ x }}</span>
</p>
</div>
<script>
const hobby = {
data() {
return {
sport: [ 'football', 'running', 'swimming' ]
}
}
};
const vm = Vue.createApp(hobby).mount('#app');
</script>
For more detail of list rendering and the directive v-for
, refer to the online reference.
The example p306.html use v-for to display an array of objects using HTML table.