实现效果如图:
使用v-bind
动态绑定和v-on
事件监听,使用props
让父组件传递数据给子组件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<style>
.container{
width: 250px;
height: 400px;
position: relative;
border-radius: 20px;
background-color: cornflowerblue;
}
.counter{
position: relative;
width: 200px;
height: 350px;
display: flex;
margin-left: 20px;
}
.counter-content{
display: inline-block;
width: 150px;
height: 150px;
margin: auto;
text-align: center;
font-size: 80px;
color: cornflowerblue;
border-radius: 20px;
background-color: lightgoldenrodyellow;
}
.btns{
height: 30px;
display: flex;
margin: 0px 15px 15px 15px;
border: 0px;
justify-content: space-between;
}
.btn{
width: 50px;
color: lightgoldenrodyellow;
outline-color: cadetblue;
border-radius: 5px;
border-color: #ffffff;
border-style: outset;
background-color: cornflowerblue;
}
</style>
<div id="app">
<cpn :value = "number"></cpn>
</div>
<template id="cpn">
<div class="container">
<div class="counter">
<span class="counter-content">{{currentValue}}</span>
</div>
<div class="btns">
<button class="btn" @click = "decrease">-</button>
<button class="btn" @click = "increase">+</button>
<button class="btn" @click = "zeroChange">归零</button>
</div>
</div>
</template>
<script src="../js/vue.js"></script>
<script>
const cpn = {
template: "#cpn",
props:['value'],
data:function(){
return{
currentValue: this.value
}
},
methods:{
decrease:function () {
this.currentValue -= 1
},
increase:function () {
this.currentValue += 1
},
zeroChange:function () {
this.currentValue = 0
}
}
}
const app = new Vue({
el: "#app",
data:{
number: 0
},
components:{
cpn
}
})
</script>
</body>
</html>