组件注册
(1.)全局组件注册
-
全局都可用
Vue.component('conponent-a',{....})
- 例:
<div id="app">
<componentA></componentA>
</div>
<template id="componenta">
<div>This is component!</div>
</template>
<script>
Vue.component('ComponentA',{
template:'#componenta',
data(){
return{}
},
methods:{}
})
new Vue({
el:'#app'
})
</script>
<div id="app">
<componentA></componentA>
</div>
<script>
Vue.component('ComponentA',{
template:'#componenta',
data(){
return{}
},
template:`<div class="blog-post">
happy new year!!
</div>`,
methods:{}
})
new Vue({
el:'#app'
})
</script>
(2.)局部组件注册
-
优势:比起全局组件来说,全局组件意味着及时你不使用某个组件了,但它仍旧会包含在你最终的构建结构中。使用户下载的javascript无谓增加。
-
只能在当前实例中使用
var ComponentA = {.....}
- 在components选项中定义想要用的组件:
var ComponentA = {...}
new Vue({
el:"#app",
components: {
'component-a':ComponentA
}
})
<div id='app'>
<component-three></component-three>
<component-two></component-two>
<component-one></component-one>
</div>
<template id="componentOne">
<h1>componentOne!!</h1>
</template>
<template id="componentTwo">
<h1>componentTwo!!</h1>
</template>
<template id="componentThree">
<h1>componentThree!!</h1>
</template>
<script>
var ComponentA = {
data:function(){
return{}
},
template:"#componentOne"
}
var ComponentB = {
data:function(){
return{}
},
template:"#componentTwo"
}
var ComponentC = {
data:function(){
return{}
},
template:"#componentThree"
}
new Vue({
el:'#app',
data:{
},
components:{
'component-three':ComponentC,
'component-two':ComponentB,
'component-one':ComponentA
}
})
</script>
var ComponentA = {
data:function(){
return{}
},
template:"#componentOne"
}
var ComponentB = {
components: {
'component-a': ComponentA
},
}
模块组件
- (1)使用模块系统,创建components目录,每个组件放置其各自的文件中。
- (2)在局部注册之前导入每个想使用的组件,例:
import ComponentA from './ComponentA'
import ComponentC from './ComponentC'
export default {
components: {
ComponentA,
ComponentC
},
}
- (3)这样ComponentA与ComponentB都可以在ComponentB中使用了。
基础组件自动化全局注册
- 在各个组件中频繁被用到的,像一个按钮,输入框之类的元素。可称之为基础组件。
- 在每个组件中都会频繁用到的,使用webpack时就可以使用
require.context
只全局注册这些通用组件 - 在应用入口文件中全局导入基础组件示例代码:
- 例:
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
)
})