Dynamically display Vue components

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-ifwithv-elseinstruction.

This is an example. Thisv-ifInstruction checknoTodosCalculated attribute, if the state attribute, it returns falsetodosContains 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>

usecomponentComponents andis

Instead of creatingv-ifwithv-elseStructure, you can build your template so that there is a placeholder that will be dynamically assigned a component.

That iscomponentThe component is indeedv-bind:isInstructions.

<component v-bind:is="componentName"></component>

componentNameIs 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: