局部注册

全局注册往往是不够理想的。比如,如果你使用一个像 webpack 这样的构建系统,全局注册所有的组件意味着即便你已经不再使用一个组件了,它仍然会被包含在你最终的构建结果中。这造成了用户下载的 JavaScript 的无谓的增加。

在这些情况下,你可以通过一个普通的 JavaScript 对象来定义组件:

  1. var ComponentA = { /* ... */ }
  2. var ComponentB = { /* ... */ }
  3. var ComponentC = { /* ... */ }

然后在 components 选项中定义你想要使用的组件:

  1. new Vue({
  2. el: '#app',
  3. components: {
  4. 'component-a': ComponentA,
  5. 'component-b': ComponentB
  6. }
  7. })

对于 components 对象中的每个属性来说,其属性名就是自定义元素的名字,其属性值就是这个组件的选项对象。

注意局部注册的组件在其子组件中不可用。例如,如果你希望 ComponentAComponentB 中可用,则你需要这样写:

  1. var ComponentA = { /* ... */ }
  2. var ComponentB = {
  3. components: {
  4. 'component-a': ComponentA
  5. },
  6. // ...
  7. }

或者如果你通过 Babel 和 webpack 使用 ES2015 模块,那么代码看起来更像:

  1. import ComponentA from './ComponentA.vue'
  2. export default {
  3. components: {
  4. ComponentA
  5. },
  6. // ...
  7. }

注意在 ES2015+ 中,在对象中放一个类似 ComponentA 的变量名其实是 ComponentA: ComponentA 的缩写,即这个变量名同时是:

  • 用在模板中的自定义元素的名称
  • 包含了这个组件选项的变量名