Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
Using conditional directives
The simplest option is to use the v-if
and v-else
directives.
Here’s an example. The v-if
directive checks the noTodos
computed property, which returns false if the state property todos
contains at least one item:
<template>
<main>
<AddFirstTodo v-if="noTodos" />
<div v-else>
<AddTodo />
<Todos :todos=todos />
</div>
</main>
</template>
<script>
export default {
data() {
return {
todos: [],
}
},
computed: {
noTodos() {
return this.todos.length === 0
}
}
}
</script>
This allows to solve the needs of many applications without reaching for more complex setups. Conditionals can be nested, too, like this:
<template>
<main>
<Component1 v-if="shouldShowComponent1" />
<div v-else>
<Component2 v-if="shouldShowComponent2" />
<div v-else>
<Component3 />
</div>
</div>
</main>
</template>
Using the component
Component and is
Instead of creating v-if
and v-else
structures, you can build your template so that there’s a placeholder that will be dynamically assigned a component.
That’s what the component
component does, with the help of the v-bind:is
directive.
<component v-bind:is="componentName"></component>
componentName
is a property of the state that identifies the name of the component that we want to render. It can be part of the state, or a computed property:
<script>
export default {
data() {
return {
componentName: 'aComponent',
}
}
}
</script>
Download my free Vue Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More vue tutorials:
- An overview of Vue.js
- The Vue.js CLI: learn how to use it
- The Vue.js DevTools
- Configuring VS Code for Vue Development
- Create your first app with Vue.js
- Vue.js Single File Components
- Vue.js templates and interpolations
- Vue.js Directives
- Vue.js Methods
- Vue.js Computed Properties
- Styling Vue.js components using CSS
- Vue.js Watchers
- Vue methods vs watchers vs computed properties
- Vue.js Filters
- Vue.js Components
- Vue.js Slots
- Vue.js Component Props
- Vue.js Events
- Vue.js Components Communication
- Vuex, the Vue.js State Manager
- Vue, use a component inside another component
- Vue, how to use a prop as the class name
- How to use SCSS with Vue.js Single File Components
- Using Tailwind with Vue.js
- The Vue Router
- Dynamically show a Vue component
- The Vue.js Cheat Sheet
- Store Vue data to localStorage using Vuex
- How to dynamically apply a class using Vue
- Vue, how to use v-model
- Vue, why data must be a function
- Roadmap to become a Vue.js developer in 2020