版权声明:本文为博主原创文章,未经博主允许不得转载。vasttian https://blog.csdn.net/u012860063/article/details/56668097
组件(Component)是 Vue.js 最强大的功能之一。
组件可以扩展 HTML 元素,封装可重用的代码。
在较高层面上,组件是自定义元素, Vue.js 的编译器为它添加特殊功能。
在有些情况下,组件也可以是原生 HTML 元素的形式,以 is 特性扩展。
当使用 DOM 作为模版时(例如,将 el
选项挂载到一个已存在的元素上), 你会受到 HTML 的一些限制,因为 Vue 只有在浏览器解析和标准化 HTML 后才能获取模版内容。尤其像这些元素 <ul>
, <ol>
, <table>
, <select>
限制了能被它包裹的元素, <option>
只能出现在其它元素内部。
eg:
a不能包含其他的交互元素(比如按钮,链接)
ul/ol只能包含li
select只能包含option和optgroup,
table只能包含thead,tbody,tfoot,tr,caption,col,colgroup,
tr只能包含th,td
违反这些规则,比如把<ul> <my-component>这种方式来组织,浏览器会把my-component提到元素的外面,导致渲染不正确。
<table> <tr is="my-component"></tr> </table>
在自定义组件中使用这些受限制的元素时会导致一些问题,例如:
<table>
<my-row>...</my-row>
</table>
自定义组件
<my-row>
被认为是无效的内容,因此在渲染的时候会导致错误。变通的方案是使用特殊的
is
属性:
<table>
<tr is="my-row"></tr>
</table>
应当注意,如果您使用来自以下来源之一的字符串模板,这些限制将不适用:
<script type="text/x-template">
- JavaScript内联模版字符串
.vue
组件
因此,有必要的话请使用字符串模版。
组件分为两种:全局组件 和 局部组件
1、全局组件
全局组件的注册须在初始化vue实例之前。
<div id="example">
<first-component></first-component>
</div>
// 注册全局组件
Vue.component('first-component', {
template: '<div>This is my first component!</div>'
});
// 创建根实例
new Vue({
el: '#example'
});
渲染为:
<div id="example">
<div>This is my first component!</div>
</div>
2、局部组件
局部组件可以通过使用某个vue组件实例注册,
这样可以使得注册的组件只在当前vue实例的作用域有效。
var Child = {
template: '<div>This is my second component!</div>'
};
new Vue({
// ...
components: {
// <second-component>组件只在父模板可用
'second-component': Child
}
});