0

我最近一直在学习 Vue.js 并努力理解组件范围的概念。

根据我从文档示例中了解到的情况,子组件只能在父组件内部工作。

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

但是,我无法达到这个结果。有人可以告诉我我哪里出错了吗?

这是我的小提琴供你演奏。

4

1 回答 1

1

当您使用本地组件作为

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

它已经在本地注册。所以你不需要打电话

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

如果您调用上述行,则您正在全局注册组件。这使得它可以在组件外部访问。所以你的代码应该是

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'
})

我还注意到您将子组件嵌套在父模板之外。您必须使用本地组件(在模板内的父组件范围内的子组件,而不是slot

于 2016-02-01T11:35:20.827 回答