Search code examples
javascriptvue.jsvue-resource

Component scope in Vue.js


I have been learning Vue.js recently and struggling to understand the concept of component scope.

From what I have understood from the example on the documentation, the child component will only work inside of a parent component.

  <parent-component>
    <my-component></my-component>
  </parent-component>

However, I am unable to achieve this result. Can someone please enlighten me where I am going wrong?

Here's my fiddle for you to play.


Solution

  • When you use a local component as

    var Parent = Vue.extend({
      template: '<div>This is a parent component</div>',
      components: {        
        'my-component': Child
      }
    })
    

    It is registered already locally. So you don't need to call

    // register
    Vue.component('my-component', Child);
    

    If you call the above line you are registering the component globally. Which makes it accessible outside the component. So your code should be

    var Child = Vue.extend({
      template: '<div>This is a child component.</div>'
    })
    
    var Parent = Vue.extend({
      template: '<div>This is a parent component <my-component></my-component></div>',
      components: {
        // <my-component> will only be available in Parent's template
        'my-component': Child
      }
    })
    
    // register
    //Vue.component('my-component', Child);
    Vue.component('parent-component', Parent);
    // create a root instance
    new Vue({
      el: '#app'
    })
    

    I also noticed that you are nesting the child component outside the parent template. You have to use the local component (child component inside the scope of the parent component which is inside the template not the slot.