组件名
在注册一个组件的时候, 我们始终需要给它一个名字. 我们在使用Vue.component注册组件时, 第一个参数就是组件名
Vue 推荐使用全小写字母且必须包含一个连字符
组件名大小写
定义组件名的方式有两种:
使用 kebab-case
使用组件: <my-component-name>
1
| Vue.component('my-component-name', {})
|
使用 OascalCase
使用组件
<my-component-name>
<MyComponentName>
1
| Vue.component('MyComponentName', {})
|
全局注册
当我们使用 Vue.component()来创建组件时, 这个组件时全局的, 我们可以在任何创建的 Vue 实例的模板中使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>JS Bin</title> </head> <body> <div id="app"> <my-component></my-component> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script> <script> Vue.component('my-component', { data() { return { text: 'Ginger' } }, template: '<div>{{ text }}</div>' }) var vm = new Vue({ el: '#app' }) </script> </body> </html>
|
局部注册
全局注册的组件即使在我们不使用的时候仍然会被包含在最终的构建结果中, 会造成用户下载的增加
我们可以通过一个普通 JavaScript 对象来定义组件, 然后在需要使用的 vue 实例中进行注册
对于 components 对象中的每个属性来说, 其属性名就是自定义元素的名字, 其属性值就是这个组件的选项对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>JS Bin</title> </head> <body> <div id="app"> <app-hellp /> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script> <script> var hello = { data: function() { return { msg: 'Hi' } }, template: '<h1>{{msg}}</h1>' } var vm = new Vue({ el: '#app', components: { 'app-hellp': hello } }) </script> </body> </html>
|
在模块系统中局部注册
我们也可以通过 require / import 使用一个模块系统.
在模块系统中局部注册
推荐创建一个 components 目录, 将每个组件防止在其各自的文件中
在模块系统中使用组件需要在局部注册之前, 我们需要导入每个想使用的组件
1 2 3 4 5 6 7 8 9 10 11
| import Home from './components/Home' import Mine from './components/Mine'
export default { components: { Home, Mine } ... }
|
基础组件的自动化全局注册
当我们使用了 webpack 构建应用时, 可以使用 require.context 只全局注册通用的基础组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import Vue from 'vue' import upperFirst from 'lodash/upperFirst' import camelCase from 'lodash/camelCase'
const requireComponent = require.context( './components', false, /Base[A-Z]\w+\.(vue|js)$/ )
requireComponent.keys().forEach(fileName => { const componentConfig = requireComponent(fileName)
const componentName = upperFirst( camelCase( fileName .split('/') .pop() .replace(/\.\w+$/, '') ) )
Vue.component( componentName, componentConfig.default || componentConfig ) })
|
全局注册必须在根 Vue 实例创建之前注册