vue3 把antd 的Modal组件作为子组件

12 篇文章 0 订阅

1.在父组件,点击一个按钮,弹窗出现,把弹窗当做子组件

<template>
  <div>
    <a-button type="primary" @click="add">新增</a-button>
    <add-material v-model="fieldData.addVisible"></add-material>
  </div>
</template>

<script setup>
import addMaterial from './components/add-material.vue';
import { ref } from 'vue';
const fieldData = ref({
  addVisible: false,
});
const add = () => {
  fieldData.value.addVisible= true;
};
</script>

<style lang="less" scoped></style>

2.子组件

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

<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
  modelValue: {
    type: Boolean,
  },
});
const emit = defineEmits(['update:modelValue']);
const modalVisible = computed({
  get: () => props.modelValue,
  set: v => emit('update:modelValue', v),
});
// 确定按钮的回调
const handleOk = () => {
  console.log('%c Line:21 🧀', 'color:#6ec1c2');
};
</script>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3中,可以通过`ref`和`teleport`来实现父组件调用组件modal。 首先,在组件中,需要使用`teleport`将modal渲染到body中,这样可以避免modal被父组件的样式影响。代码如下: ```html <template> <teleport to="body"> <div class="modal"> <!-- modal内容 --> </div> </teleport> </template> ``` 然后,在父组件中,需要使用`ref`来获取组件的实例,并通过调用组件的方法来打开或关闭modal。代码如下: ```html <template> <div> <button @click="openModal">打开modal</button> <ChildComponent ref="childComponentRef" /> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent, }, methods: { openModal() { this.$refs.childComponentRef.openModal(); }, }, }; </script> ``` 在组件中,需要定义一个`openModal`方法来打开modal,并通过`emits`来向父组件发送事件。代码如下: ```html <template> <teleport to="body"> <div class="modal" v-if="visible"> <!-- modal内容 --> </div> </teleport> </template> <script> import { defineEmits } from 'vue'; export default { emits: ['update:visible'], data() { return { visible: false, }; }, methods: { openModal() { this.visible = true; this.$emit('update:visible', true); }, closeModal() { this.visible = false; this.$emit('update:visible', false); }, }, }; </script> ``` 在父组件中,需要通过`v-model`来监听组件的`visible`属性,并在组件的`update:visible`事件触发时更新`visible`属性。代码如下: ```html <template> <div> <button @click="visible = true">打开modal</button> <ChildComponent v-model:visible="visible" /> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent, }, data() { return { visible: false, }; }, }; </script> ``` 这样,就可以实现父组件调用组件modal了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值