- Learn by example
Make an RPG
Vue Implementations

Example of How to use v-bind:is in Dynamic Components

is let's you statically choose which component it should be.

<component is='flower'>
Vue.component('flower', { template: `<div>I'm a flower</div>` }); Vue.component('tree', { template: `<div>I'm a tree</div>` });

Go ahead and try it out and hit the run button. You should see that the flower component is shown because is='flower'.

Now change is='flower' to is='tree' and rerun it.

Now, let's add v-bind to it, to make it dynamic. Notice, that "thing" is now interpretted as a variable and not a constant string because of the v-bind. This let's you choose a component dynamically.

<component v-bind:is='thing'>
var app = new Vue({ el: '#demo', data: { thing: 'bush' } });
Change thing: 'flower' to thing: 'tree'

DOM parsing errors

Some tags like table have restrictions on what can be inside. So, if you create your own components and place them in a table, you could end up with an error. Here's an example

<table> <my-component></my-component> </table>

Now, HTML is a fairly permissive scripting language so it may still render things, but it's not technically correct and you can end up with errors. This is where is can help out. Observe:

<table> <tr is='my-component'></tr> </table>

Now the code is correct, and we can have our custom component. These limitations do not apply when you're getting your string templates from one of the following sources:

  • String templates (template: `...`)
  • Single file *.vue components
  • Script tags:
    <script type="text/x-template"> </script>

In the next lesson, we will learn about Example of How to use keep-alive with Dynamic Components

Get the Latest Tutorial Updates
<< >>