12组件
# 组件
组件是可复用的模块。可复用指的是同一个模块,传不同的数据,显示不同的效果。
# 创建组件
# 1、全局组件
只要注册了,在任何地方都能使用。
<div id="app">
<!-- 使用组件 -->
<my-component></my-component>
<my-component></my-component>
<my-component></my-component>
</div>
//注册全局组件
//驼峰式:myComponent
Vue.component("myComponent",{
template:"<div>我的组件</div>"
})
new Vue({
el: "#app",
data: {
msg:""
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
%accordion% 全局组件(全局注册)🚀 %accordion%
<div id="app">
<component2></component2>
</div>
<script>
// 全局组件(全局注册)
Vue.component("myComponent1", {
template: "<div>组件1</div>",
});
Vue.component("component2", {
template: `
<div>
组件2
<my-component1></my-component1>
</div>
`,
});
new Vue({
el: "#app",
data: {
msg: "",
},
});
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
%/accordion%
# 2、局部组件
在需要用到的地方进行注册,才能使用。
// 注册局部组件
let myComponent2 = {
template:"<div>我的组件2</div>"
}
//根组件
new Vue({
el: "#app",
data: {
msg:""
},
components:{
myComponent2
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
%accordion% 局部组件(区域注册)🚀 %accordion%
<div id="app">
<my-component2></my-component2>
</div>
<script>
//局部组件(区域注册)
let myComponent1 = {
template: "<div>我是组件1</div>",
};
let myComponent2 = {
template: `
<div>
我是组件2
<my-component1></my-component1>
</div>
`,
//注册区
components: {
myComponent1,
},
};
new Vue({
el: "#app",
components: {
myComponent2,
},
});
</script>
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
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
%/accordion%
# 3、组件里面的data数据只能是函数
如果是对象,复用的所有组件都会共用同一个数据
let myComponent1 = {
template:"<div>{{msg}}</div>",
data(){
return{
msg:"hi"
}
}
}
//根组件
new Vue({
el: "#app",
data:{
msg:"hello"
},
components:{
myComponent1
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 父子组件概念
父:被注册的组件
子:注册的组件
//儿子
let myComponent2 = {
template:"<div>组件2</div>",
}
//爸爸
let myComponent1 = {
template:"<div>组件1</div>",
components:{
myComponent2
}
}
//根组件(爷爷)
new Vue({
el: "#app",
data:{
msg:"hello"
},
components:{
myComponent1
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
编辑 (opens new window)
上次更新: 2023/08/06, 00:38:41