Solution 1

The parent component transmits values to its children, which are received by props. At the same time, watch is used to monitor the changes of values transmitted by the parent component, and then dynamically modify the visible value in the popover component. When the child component closes the popover, the parent component is notified through emit

<template> I am the parent component <InsuranceProductList :visible="visible" @popupClose="onClosePopup" />
</template>
<script>
import { ref, reactive, toRefs } from "vue";
import InsuranceProductList from "components/InsuranceProductList";

// Control the insurance product popup
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>
Copy the code
<template> I am the child component <van-overlay :show="showPopup" duration="0.1"> Content </van-overlay> </template><script>
import { ref, watchEffect } from "vue";

// Control the popover
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>
Copy the code

Solution 2

The child component uses the data passed by the parent component directly in the calculation property, without listening for changes later

Child components:

<template> I am a child component <van-overlay :show="showPopup" duration="0.1"> Contents </van-overlay> </template> <script> import {computed  } from "vue"; // Control popup 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>Copy the code

conclusion

The usage in the parent component is consistent, and the difference in the child component is whether it is implemented using Watch or computed.