vue2.0笔记(四)——组件和模板

组件 Component

组件(Component)是 Vue.js 最强大的功能之一。
组件可以扩展 HTML 元素,封装可重用的代码(即模板template)。

全局组件

全局组件意味着所有实例都可以使用这个组件

1
2
3
4
5
6
<div id="app">
<my-com></my-com>
</div>
<div id="app1">
<my-com></my-com>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//注册组件
Vue.component('my-com',{
template:'<h1>{{msg}}</h1>',
data:function () {
return{
msg:'hello'
}
}
});
//一个实例
new Vue({
el:'#app'
});
//又一个实例
new Vue({
el:'#app1'
});

※实例基本没什么限制,只要不是挂载到本身就可以☞ el:'my-com'是行不通的
※此外组件的data要在注册时候写,并且data里只能是个return出来的返回值

局部组件

我们也可以在实例选项中注册局部组件,这样组件只能在这个实例中使用

1
2
3
4
5
<!-- 可以注册多个组件和模板 -->
<div id="app">
<com-one></com-one>
<com-two></com-two>
</div>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//data可以先提出来,在组件里直接返回data即可
var data={
msg1:'hello',
msg2:'vue'
}
var temOne={
template:'<h1>{{msg1}}</h1>',
data:function () {
return data;
}
};
var temTwo={
template:'<h1>{{msg2}}</h1>',
data:function () {
return data;
}
};
new Vue({
el:'#app',
components:{
'com-one':temOne,
'com-two':temTwo
}
});

模板

template里面内容很多,已经不仅仅是一行代码的时候,我们可以在html部分添加<template>标签并且引用它

1
2
3
4
5
6
7
8
9
10
11
12
13
<body>
<div id="app">
<poem></poem>
</div>
<!-- 在html里直接写模板即可 -->
<template id="my-temp">
<dl>
<dt>今日は 风が 骚がしいな</dt>
<dd>天気がいいから</dd>
<dd>散歩しましょう</dd>
</dl>
</template>
</body>

1
2
3
4
5
6
Vue.component('poem',{
template:'#my-temp'
})
var vm=new Vue({
el:"#app"
})

注意: 因为Vue只有在浏览器解析和标准化HTML后才能获取模版内容。尤其像这些元素<ul> 、<ol>、<table>、<select>限制了能被它包裹的元素,<option>只能出现在其它元素内部。

1
2
3
4
5
6
7
8
<!--这种是不行的,会报错-->
<table>
<my-row>...</my-row>
</table>
<!--要通过is属性来处理-->
<table>
<tr is="my-row"></tr>
</table>

Tips: 长命名在html里使用kebab-case短横线写法,js里采取camelCase驼峰命名法

动态组件

多个组件可以使用同一个挂载点,然后动态地在它们之间切换。使用保留的 元素,动态地绑定到它的 is 特性

1
2
3
<div id="app">
<component v-bind:is="currentView"></component>
</div>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var comA = {
template: '<h1>a</h1>'
};
var comB = {
template: '<h2>b</h2>'
}
var vm = new Vue({
el: "#app",
components: {
"com-a": comA,
"com-b": comB
},
data: {
currentView: "com-b"
}
})

keep-alive

如果把切换出去的组件保留在内存中,可以保留它的状态或避免重新渲染。为此可以添加一个 keep-alive 指令参数:

1
2
3
4
5
<keep-alive>
<component :is="currentView">
<!-- 非活动组件将被缓存! -->
</component>
</keep-alive>

子组件索引

尽管有 props 和 events ,但是有时仍然需要在 JavaScript 中直接访问子组件。为此可以使用 ref 为子组件指定一个索引 ID

1
2
3
<div id="parent">
<child-com ref="profile" name="mary"></child-com>
</div>

1
2
3
4
5
6
7
8
9
10
Vue.component('child-com', {
template: '<span>{{name}}</span>',
props: ["name"]
})
var parent = new Vue({
el: "#parent"
})
// 访问子组件
var child = parent.$refs.profile;
console.log(child.name);