Search code examples
vuejs2vue-component

Why child created with new Vue.extend() does not get rendered in parent


Why child does not get rendered in parent even though component is created with a component constructor returned with Vue.extend()

var newChild = Vue.extend({
  template: '<div> {{ childMsg }} </div>',
  data() {
    return {
      childMsg: 'Child World'
    }
  }
})

var child = new newChild()

new Vue({
  el: '#app',
  data: {
    msg: 'Hello World'
  },
  components: {
      child: child
  }
})

template

<div id="app">
  <div>{{msg}}</div>
  <child></child>
</div>

Solution

  • The extend method is to extend an already existing component. In this case, what you want is to create a new component. You can do this by using the component method, and the first argument, preceding the component properties, is the component name.

    Knowing that, you could adapt the code like this:

    var newChild = Vue.component('child', {
      template: '<div> {{ childMsg }} </div>',
      data() {
        return {
          childMsg: 'Child World'
        }
      }
    })
    
    new Vue({
      el: '#app',
      data: {
        msg: 'Hello World'
      },
      components: {
          child: newChild
      }
    })