1.组件的定义
组件其实就是把一整个页面分成很多个小的部分,比如一个页面可以分成头部,尾部等等。这样子,就可以像组装零件一样将组件组合起来形成页面,大大提高了代码的复用性,代码组织起来也更有逻辑。
2.全局组件
全局组件也就是作用域是全局的组件,也就是在这个页面的任何位置都可以使用的组件
<script>
//将全局组件hello和world组合起来形成了一个页面
const app = Vue.createApp({
template: "<div><hello/><world/></div>",
});
//全局组件hello
app.component("hello", {
template: "<div>hello</div>",
});
//全局组件world
app.component("world", {
template: "<div>world</div>",
});
//挂载在root节点上
const vm = app.mount("#root");
</script>
3.局部组件
局部组件就是作用域是局部的组件,必须要通过某种方式通知要使用的组件局部组件的存在
// 局部组件HelloWolrd
const HelloWorld = {
template: `<div>hello world</div>`,
};
//局部组件Counter
const Counter = {
data() {
return {
count: 1,
};
},
template: `<div @click="count+=1">{{count}}</div>`,
};
//使用components对象注册局部组件
const app = Vue.createApp({
components: {
counter: Counter,
helloWorld: HelloWorld,
},
template: `
<div>
<counter/>
<helloWorld/>
</div>`,
});
4.全局组件和局部组件的优劣
- app.component 注册的组件是全局组件 定义了随处可用 性能不高 使用起来简单
- 在Vue.createApp中components:{}注册了之后是局部组件 注册之后才能使用 性能比较高