简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM