计数器通过组件的props和event实现
<template id="app1">
<div>
<h2>{{acount}}</h2>
<button @click="add">+</button>
<button @click="sub" v-bind:disabled='acount<=1'>-</button>
</div>
</template>
这是计数器的组件,通过add进行++,sub进行--;
components:{
cpn1:{
template:'#app1',
props:{
acount:{
type:Number,
required:true
}
},
data:function(){
return{
dcount:this.acount //通过data renturn一个数据来获取acount的值
}
},
methods:{
add:function(){
this.dcount++
this.$emit('add',this.dcount) //进行发射
},
sub:function(){
this.dcount--
this.$emit('sub',this.dcount)//进行发射
}
}
}
}
data:{
count = 5
}
madd(value){
this.count = value
}
msub(value){
this.count = value
}
<div id="app">
<!--把父组件的count绑定到子组件的acount中,把子组件的add方法发送到madd方法中,sub方法发送到msub中--> <cpn1 v-bind:acount="count" @add="madd" @sub="msub"></cpn1> </div>
接受代码

浙公网安备 33010602011771号