组件(Component)是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装可重用的代码。在较高层面上,组件是自定义元素,Vue.js 的编译器为它添加特殊功能。在有些情况下,组件也可以是原生 HTML 元素的形式,以 is 特性扩展。
1.创建和注册组件:
<template>
<div>
<label>Username</label>
<input placeholder="username"><br/>
<label>Username password</label>
<input placeholder="password" key="username-possword">
<slot name="slot_h2"><h2>这里是备用内容,只有当没有插入内容的时候才显示</h2></slot>
</div>
</template>
<script>
export default {
data () {
return {
}
},
created () {
},
methods: {
},
}
</script>
要把这个构造器用作组件,需要用
Vue.component(tag, constructor)
注册(这个注册是全局的):
//全局注册组件,tag 为 my-component
Vue.component('my-component', MyComponent)
//如果用懒加载的话
Vue.component(
'my-components',
() => System.import('./../../components/modules/MyComponents')
)
组件在注册之后,便可以在父实例的模块中以自定义元素 <my-component> 的形式使用。要确保在初始化根实例之前注册了组件:
<div id="example">
<my-component></my-component>
</div>