组件
组件允许我们将 UI 划分为独立的、可重用的部分,并且可以对每个部分进行单独的再次重新编辑,就如同一个树状解构,一层一层的组合
组件的注册
vue指令的本质是自定义标签属性
vue组件的本质就是自定义标签
组件的注册有两种方式
1.全局组件
大量复用的组件建议注册成全局组件
全局组件注册在vue实例上
使用 .component(第一个参数是组建名称,第二个参数是组建定义(第二个是一个函数))
<template id="counter">
<button @click="count++">点赞: {{count}}</button>
</template>
<script>
app.component('button-counter', {
//将上方的coubter与template绑定
template: '#counter',
data() {
return {
count: 0,
};
},
});
</script>
2.局部组件
不常用的组件建议注册成局部组件
局部组件注册在vue实例的参数中
const app = Vue.createApp({
components: {
// 这里使用规范的驼峰命名法, 但是在html中要转为蛇形
buttonCounter: {
template: '#counter',
data() {
return {
count: 0,
};
},
},
},
});
app.mount('#app');
组件的传参(通信)
父组件向子组件传参
<body>
<div id="app">
<!-- 使用自定义属性将父组件参数传入子组件中 -->
<button-counter username="admin" email="498446472@qq.com"></button-counter>
</div>
<template id="counter">
<p>用户名: {{username}}</p>
<p>邮箱: {{email}}</p>
</template>
<script>
const app = Vue.createApp();
app.component('button-counter', {
// props: 用数组接收父组件传入的自定义属性做为载体的参数
props: ['username', 'email'],
template: '#counter',
});
app.mount('#app');
</script>
子组件像父组件传参(监听子组件事件)
<div id="app">
<button-counter @review-count="review"></button-counter>
</div>
<template id="counter">
<button @click="count++">点赞: {{count}}</button>
<!-- 发布订阅 -->
<!-- $emit(自定义事件名称, 向父组件传递的参数(可选)) -->
<!-- $emit('reviewCount', this.count) -->
<button @click="$emit('reviewCount', this.count)">评价</button>
</template>
<script>
const app = Vue.createApp({
methods: {
review(count) {
console.log(count);
if (count >= 10) alert('大家吃了吗?');
},
},
});
app.component('button-counter', {
template: '#counter',
data() {
return {
count: 0,
};
},
});
app.mount('#app');
父->子: props: [….]
子->父:
1 子发布事件: $emit(自定义事件,参数(参数可选))
2 父订阅事件: @自定义事件(…args)