一、组件
组件是可复用的 Vue 实例,且带有一个名字
因为组件是可复用的 Vue 实例,所以它们和Vue接收相同的选项,例如 data 、 computed 、 watch 、 methods 以及生命周期钩子等。
1.通过 app.component 来创建组件
- 注册组件
Vue.createApp({
// 注册组件
components: {
steper
},
data() {
return {
}
},
}).mount(".app")
- 定义组件
// 定义组件
const steper = {
template: `
<span>
<button @click="num-=step" :disabled="num<=mini">-</button>
<input type="text" v-model.number="num">
<button @click="num+=step" :disabled="num>=max">+</button>
</span>`,
}
- 使用组件
<div class="app">
<steper></steper><br>
<steper></steper>
</div>
</body>
2.组件的参数传递
- 父传子 props
<step :num="10"></step>
//接收
props:{
"num":{type:Number,default:1}
},
//使用
data(){return {n:this.num}}
对象与数组的默认值必须是函数的返回值
- 子传父 emit事件
//在steper内部
this.$emit("numchange",this.num)
numchange事件名称,this.num 事件值
//父组件
<steper @numchange="w1=$event">
$event 就是子组件通过numchange传递过来的值 this.num
组件案例 swiper幻灯片效果
- css
<style>
* {
margin: 0;
padding: 0;
}
.app img {
width: 800px;
}
.app .swiper {
position: relative;
width: 800px;
margin: 20px auto;
}
.swiper .btn {
font-size: 20px;
position: absolute;
padding: 8px 20px;
color: #000;
background-color: #ccc;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
}