在我们开发uniapp时会用到uview的组件,很方便,但项目中可能会对组件进行二次修改,设置成时候自己项目的功能、样式,如果多处需要用到,可能需要进行二次封装,这时候就会涉及到父子传参等问题,这篇文章主要是为了记录解决父组件控制子组件的显示隐藏问题,下面以u-popup组件为例吧!
<!--子组件-->
<template>
<view class="payment">
<!-- 弹出框 -->
<u-popup mode="bottom" v-model="show" :mask-close-able='false'>
<view class="popUpBox">
<view class="popUpBoxPriceBox flex">
<view class="proceeds">收款: <text>¥520.00</text></view>
<view class="close" @click="onClose">取消</view>
</view>
<view class="paymentBigBox ">
<view class="onePayment flex" v-for="(item,i) in modeOfPayment" @click="onPay(i)">
<image :src="item.image"></image>
<text>{{item.name}}</text>
</view>
</view>
</view>
</u-popup>
</view>
</template>
<script>
export default {
name:"payment",
props: {
showModal:{
type:Boolean,
}
},
data() {
return {
show: false, //弹出框显示状态
modeOfPayment: [
{
image: '../static/settleAccounts/weixin.png',
name: '微信'
},
{
image: '../static/settleAccounts/zhifubao.png',
name: '支付宝'
},
{
image: '../static/settleAccounts/yue.png',
name: '余额'
},
],
};
},
watch:{
//因为是单项数据流,v-modal控制的组件显示隐藏,父组件不可以通过props内的参数直接改变子元素参数,所以我们通过watch来监控数据的变化,间接修改show的数据
showModal(val) {
this.show=val
}
},
methods:{
onClose(){
this.show=false
this.$emit('close',this.show) //通知父组件隐藏了
},
}
}
</script>
<!--父组件-->
<template>
<view>
<button @click="showPay">点击显示</button>
<payment :showModal="showPay" @close="onclose"></payment>
</view>
</template>
<script>
import payment from "../../components/payment.vue"
export default {
data() {
return {
showPay:false,//显示支付方式
}
},
components: {
payment
},
methods:{
onclose(show){
this.showPay=show
console.log(show,"子组件传过来的值----")
},
showPay(){
this.showPay=true //传给子组件动态控制显示隐藏
}
}
}
</script>