Vue学习笔记2- 组件

组件基础

自定义组件,生命类似于Vue实例。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<body>

<button-center> </buton-center>

<script>
new Vue.component("button-center",{
data:function(){
<> return {dd:1}
},
template:"<button v-on:click="dd++"> {{dd}} </button>"

})

</script>
</body>

上面基础组件自定义中,componentdatacomputemethods等与Vue实例类似,但是注意data中数据要使用方法返回.因为这样是了每个组建的实例化的时候,都可以满足单独维护。

通过prop向子组件传递数据

props可以用来添加自定义属性:

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

<body>
<div id="app">

<btn title="惦记我"></btn>


</div>



<script>

Vue.component("btn",{

props:["title"],
template:"<el-button > {{title}}</el-button>"
})

var vn=new Vue({
el:"#app",
})
</script>

</body>

如果当传递的数据的数据过多的时候,可以直接传递在props中传递 对象。li例如:

1
2
3
4
5
6
7
<blog-post v-bind:post="x"> </blog-post>

Vue.component("blog-post",{
props:['post'],
template:"<ul> <li> {{post.title}} </li> <li>{{post.id}} </li></ul>"

})

动态组件

使用动态组件,上述内容可以通过 Vue 的<component>元素加一个特殊的 isattribute 来实现:

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<div   id="content"> 
<div style="text-align: center;">

<el-button-group style="text-align: center;">
<el-button type="primary" v-for="tab in tabs"
v-bind:type="tab"
v-bind:class="['tab-button', { active: currentTab === tab }]"
v-on:click="currentTab = tab"

> {{tab}}

</el-button>
</el-button-group>

</div>

<component v-bind:is="currentTabComponent" class="tab">
</component>

</div>


</div>

<script>

Vue.component("tabhome",{
template:"<label> home page </label>"

})
Vue.component("tabtag",{
template:"<label> tage page </label>"

})
Vue.component("tababout",{
template:"<label> about page </label>"

})

new Vue({
el:"#content",
data:{

currentTab:"home",
tabs:["home","tag","about"]
},
computed:{

currentTabComponent:function(){
return "tab"+this.currentTab
}
}
})
</script>

Copyright © 2016 - 2020 Life-long Learning All Rights Reserved.

UV : | PV :