效果如下:
1.在components中新建个counter.vue 组件
<template>
<!-- 计数器 -->
<view class="counter-box">单位 : 个
<view class="counter">
<text class="reduce-add" @click="addReduce(0)">-</text>
<text class="amount" v-text="count"></text>
<text class="reduce-add" @click="addReduce(1)">+</text>
</view>
<view style="text-align: right;color: #F7621C" v-text="hint"></view>
</view>
</template>
<script>
export default {
data(){
return {
hint: '' // 超出最大限制数量
}
},
props: ['count','minZero'], // 父传子
methods: {
// 增加,减少按钮 id为0减少,为1增加
addReduce(id) {
if(id === 0) {
if(this.count > 1) {
this.count--
// 子传父
this.$emit('countNum',this.count)
this.hint = ''
}else(id === 1){
this.hint = '不能再减少啦'
return
}
}else {
if(this.count < this.minZero){
this.count++
this.hint = ''
this.$emit('countNum',this.count)
}else {
this.hint = '超出最大购买数量'
}
}
}
}
}
</script>
<style lang="less">
.counter-box {
// position: absolute;
// top: 210upx;
// right: 34upx;
font-size: 20upx;
color: #7F8389;
vertical-align: top;
.counter {
margin-left: 12upx;
font-size: 26upx;
vertical-align: bottom;
display: inline-block;
.reduce-add {
display: inline-block;
border: 1px solid #707070;
width: 42upx;
height: 42upx;
line-height: 40upx;
text-align: center;
font-size: 46upx;
vertical-align: middle;
}
.amount {
display: inline-block;
width: 78upx;
height: 42upx;
line-height: 42upx;
text-align: center;
border-top: 1px solid #707070;
border-bottom: 1px solid #707070;
vertical-align: middle;
color: #000;
}
}
}
</style>
2.父组件应用的部分代码
<template>
<view class="box">
<Counter @countNum="countNumber" :count="makeZero" :minZero="minZero"
class="count"></Counter>
</view>
</template>
<script>
import Counter from '../../components/counter.vue'
export default {
data() {
return {
makeZero: 1, // 父组件得到的数量
minZero: 0, // 最大购买限制
}
},
components: {
Counter
},
methods: {
// 得到子组件数量,并把值赋值给父组件
countNumber(id) {
console.log(this.makeZero)
if(id <= this.courseDetail.limitNum){
this.makeZero = id
console.log('数量',id)
}
}
}
}
</script>
结语:
在vue中比较常用的组件传值有:父传子,子传父。而兄弟组件传值比较少用,本例子也没使用到,请自行看vue文档,
另外补充下知识点:
1.父传子
(1).在子组件中接收 props: [‘xxx’]
(2).父组件传 :xxx=“传的值”
2.子传父
(1). 在子组件定义传值的方法 this.$emit(‘xxx’,传的值)
(2). 在父组件引用方法 <view @xxx=“example”>
(3). 利用方法接收子组件的值
example(id) {
console.log(id)
}