# vue-cli 中的组件定义及使用

在 vue-cli 中,借助于 webpack 的『编译』能力,我们可以将组件的定义,写在一个单独的 .vue 文件中。

<template>
  <div> <!-- Vue 要求组件只有唯一的顶点 -->
  </div>
</template>

<script>
  export default {
    data() {
      return { };
    }
  }
</script>

<style scoped>
</style>

这里需要注意的是,组件的定义通常是使用驼峰命名法:XxxYyyZzz,但是在使用时必须使用串型命名法:<xxx-yyy-zzz></xxx-yyy-zzz>

# 1. 全局导入

在项目的入口 main.js 中引入,并声明组件:

import HelloWorld from "@/components/HelloWorld.vue";
import Goodbye from "@/components/Goodbye.vue";

Vue.component('HelloWorld', HelloWorld);
Vue.component('Goodbye', Goodbye);

然后,你就可以在任意的地方使用 HelloWorld 和 Goodbye 组建了:

<HelloWorld></HelloWorld>
<Goodbye></Goodbye>

# 2. 局部导入

在你要使用组件的地方,即,父组件的 .vue 文件中 import 子组件:

import Hello from '@/xxx/yyy/zzz/Hello.vue' // .vue 可省略

在父组件的 components 中去声明使用子组件:

export default {
    ...
    components: {
      HelloWorld,
      Goodbye
    },
    ...
}

在父组件的页面上使用子组件:

<HelloWorld></HelloWorld>
<Goodbye></Goodbye>