效果如下:
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)
}