Vue 3 父子组件通信语法糖 .sync 实现

本文描述了一个Vue应用中父组件如何通过v-model与子组件(如Modal)进行数据交互,以及使用了AntDesignVue库的Button组件。
摘要由CSDN通过智能技术生成

父组件:

<template>
  <nav>导航栏</nav>
  <main>
    <a-button type="primary" @click="visible = true">父组件</a-button>
    <ImgList />
  </main>
  <child-modal v-model:visible="visible"></child-modal>
</template>

<script>
import ImgList from './components/ImgList.vue'
import { Button } from 'ant-design-vue'

export default {
  name: 'App',
  components: {
    ImgList,
    AButton: Button,
  },
  data() {
    return {}
  },
}
</script>

<script setup>
import { ref, getCurrentInstance } from 'vue'
const { proxy, ctx } = getCurrentInstance()
import ChildModal from './components/modal.vue'
const visible = ref(false)

const msg = ref('success')
setTimeout(() => {
  proxy.$message.success(msg.value)
  console.log(proxy, ctx)
}, 1000)
</script>

子组件:

<template>
  <a-modal v-model:visible="show" title="Basic Modal" @ok="handleOk">
    <p>Some contents...</p>
    <p>Some contents...</p>
    <p>Some contents...</p>
  </a-modal>
</template>

<script setup>
import { computed, defineProps, defineEmits} from 'vue'
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
})
const $emit = defineEmits(['update:visible'])
const show = computed({
  get() {
    return props.visible
  },
  set(v) {
    $emit('update:visible', v)
  },
})
const handleOk = e => {
  console.log(e)
  show.value = false
}
</script>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值