component组件

  1. 1. 全局组件
  2. 2. 局部变量

全局组件

全局注册也就是说它们在注册之后可以用在任何新创建的组件实例的模板中

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
<div id="app">
<component-a></component-a>
<component-b></component-b>
<component-c></component-c>
</div>

<script type="text/javascript">
const param = {
data() {},
methods:{}
}
const app = Vue.createApp(param);
app.component('component-a', {
data() {
return{
title: '这是a'
}
},
methods:{},
template:"<div style='color:red;text-align: center'>{{title}}</div>"
});

app.component('component-b', {
data() {
return{
title: '这是b'
}
},
methods:{},
template:"<div style='color:blue;text-align: center'>{{title}}</div>"
});

app.component('component-c', {
data() {
return{
title: '这是c'
}
},
methods:{},
template:"<div style='color:pink;text-align: center'>{{title}}</div>"
});

app.mount('#app')
</script>

局部变量

全局注册往往是不够理想的。比如,如果你使用一个像 webpack 这样的构建系统,全局注册所有的组件意味着即便你已经不再使用其中一个组件了,它仍然会被包含在最终的构建结果中。这造成了用户下载的 JavaScript 的无谓的增加。

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
<div id="app">
{{age}}
<inner-com></inner-com>
</div>

<script type="text/javascript">
const inner = {
data() {
return {
age: 20
}
},
template: "<div style='background-color: red'>{{age}} </div>"
}

const param = {
data() {
return {
age: 10
}
},
components: {
innerCom: inner
}
}
const app = Vue.createApp(param)
app.mount('#app')

</script>

注意局部注册的组件在其子组件中不可用