父子组件实现双向数据绑定

以下案例通过 vue3ant-design-vue 实现

  • 父组件 parent.vue
 <template>
	 <a-button @click= visible = true> 点击我 </a-button>
	 <SonModal v-model:visible="visible" />
 </template>
 
 <script setup>
  import { ref } from 'vue';
  import SonModal from "./SonModal.vue";
  const visible = ref(false);
 </script>
  • 子组件 SonModal.vue
 <template>
   <a-modal
    v-if="visible"
    v-model:visible="visible"
    title="弹窗"
    @cancel="close">
    <p>内容...</p>
    <p>内容...</p>
    <p>内容...</p>
   </a-modal>
 </template>
 
 <script setup>
   import { ref, defineProps, defineEmits } from 'vue';
   	
   const props = defineProps({
		visible: Boolean
   });
   const v = ref(props.visible);
	
   watch(
  	 () => props.visible,
   	 (value) => {
       v.value = value;
  	 }
   );
	
   const emit = defineEmits(['update:visible'])
	// 关闭弹窗
   const close = () => {
  	  emit('update:visible', v.value)
   }
 </script>
Logo

前往低代码交流专区

更多推荐