解决思路1
父组件通过给子组件传值,子组件通过props接收,同时使用watch监听父组件传值的变化,然后动态的修改弹窗组件中visible的值 ,当子组件关闭弹窗的时候 通过emit发布通知父组件
<template>
我是父组件
<InsuranceProductList :visible="visible" @popupClose="onClosePopup" />
</template>
<script>
import { ref, reactive, toRefs } from "vue";
import InsuranceProductList from "components/InsuranceProductList";
// 控制 保险产品弹窗
const usePopup = () => {
const visible = ref(false);
const onOpenPopup = () => {
visible.value = true;
};
const onClosePopup = () => {
visible.value = false;
};
return {
visible,
onOpenPopup,
onClosePopup,
};
};
export default {
components: {
InsuranceProductList,
},
setup() {
const { visible, onOpenPopup, onClosePopup } = usePopup();
return {
visible,
onOpenPopup,
onClosePopup,
};
},
};
</script>
<template>
我是子组件
<van-overlay :show="showPopup" duration="0.1">
内容
</van-overlay>
</template>
<script>
import { ref, watchEffect } from "vue";
// 控制弹窗
const usePopup = (props, emit) => {
const showPopup = ref(false);
watchEffect(() => {
showPopup.value = props.visible;
});
const onHandleClose = () => {
emit("popupClose");
};
return {
showPopup,
onHandleClose,
};
};
export default {
props: {
visible: {
type: Boolean,
default: false,
},
},
setup(props, { emit }) {
const { showPopup, onHandleClose } = usePopup(props, emit);
return {
showPopup,
onHandleClose,
};
},
};
</script>
解决思路2
子组件直接在计算属性里使用 父组件传递来的数据,不用监听了之后再改变 子组件:
<template>
我是子组件
<van-overlay :show="showPopup" duration="0.1">
内容
</van-overlay>
</template>
<script>
import { computed } from "vue";
// 控制弹窗
const usePopup = (props, emit) => {
const showPopup = computed(() => {
return props.visible;
});
const onHandleClose = () => {
emit("popupClose");
};
return {
showPopup,
onHandleClose,
};
};
export default {
props: {
visible: {
type: Boolean,
default: false,
},
},
setup(props, { emit }) {
const { showPopup, onHandleClose } = usePopup(props, emit);
return {
showPopup,
onHandleClose,
};
},
};
</script>
总结
父组件中的用法一致,子组件中区别是使用
watch
还是computed
来实现。