With Vue, you can use components to define the application layout. At the beginning, you manually place the components in the desired location, but at some point, you need a more flexible way to show or hide the components based on the application state.
Use conditional instructions
The easiest option is to usev-if
withv-else
instruction.
This is an example. Thisv-if
Instruction checknoTodos
Calculated attribute, if the state attribute, it returns falsetodos
Contains at least one:
<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 can solve the needs of many applications without the need for more complicated settings. Conditional statements can also be nested, as shown below:
<template>
<main>
<Component1 v-if="shouldShowComponent1" />
<div v-else>
<Component2 v-if="shouldShowComponent2" />
<div v-else>
<Component3 />
</div>
</div>
</main>
</template>
usecomponent
Components andis
Instead of creatingv-if
withv-else
Structure, you can build your template so that there is a placeholder that will be dynamically assigned a component.
That iscomponent
The component is indeedv-bind:is
Instructions.
<component v-bind:is="componentName"></component>
componentName
Is the attribute of the state, used to identify the name of the component we want to present. It can be part of the state, or it can be a calculated attribute:
<script>
export default {
data() {
return {
componentName: 'aComponent',
}
}
}
</script>
Download mine for freeVue manual
More vue tutorials:
- Vue.js overview
- Vue.js CLI: Learn how to use it
- Vue.js development tools
- Configure VS code for Vue development
- Create your first application with Vue.js
- Vue.js single file component
- Vue.js templates and interpolation
- Vue.js instructions
- Vue.js method
- Vue.js calculated attributes
- Use CSS to style Vue.js components
- Vue.js observer
- Vue method vs observer vs calculated property
- Vue.js filter
- Vue.js components
- Vue.js slot
- Vue.js component props
- Vue.js activities
- Vue.js component communication
- Vuex, Vue.js state manager
- Vue, use a component inside another component
- Vue, how to use prop as a class name
- How to use SCSS with Vue.js single file component
- Use Tailwind in Vue.js
- Vue router
- Dynamically display Vue components
- Vue.js cheat sheet
- Use Vuex to store Vue data to localStorage
- How to use Vue dynamic application class
- Vue, how to use the v model
- Vue, why data must be functions
- Roadmap to become a Vue.js developer in 2020