打开弹窗&l…">
当前位置:首页 > VUE

vue实现弹窗代码

2026-03-08 22:34:11VUE

基础弹窗实现

使用Vue的v-ifv-show控制弹窗显示隐藏:

<template>
  <button @click="showModal = true">打开弹窗</button>
  <div class="modal" v-if="showModal">
    <div class="modal-content">
      <span class="close" @click="showModal = false">&times;</span>
      <p>弹窗内容</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showModal: false
    }
  }
}
</script>

<style>
.modal {
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  width: 80%;
  max-width: 500px;
}

.close {
  float: right;
  cursor: pointer;
}
</style>

组件化弹窗

创建可复用的弹窗组件:

<!-- Modal.vue -->
<template>
  <transition name="fade">
    <div class="modal" v-if="show">
      <div class="modal-content">
        <slot></slot>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  props: {
    show: Boolean
  }
}
</script>

父组件中使用:

<template>
  <button @click="showModal = true">打开弹窗</button>
  <Modal :show="showModal" @close="showModal = false">
    <p>自定义弹窗内容</p>
  </Modal>
</template>

使用第三方库

安装vue-js-modal库:

npm install vue-js-modal

全局注册:

import VModal from 'vue-js-modal'
Vue.use(VModal)

使用示例:

<template>
  <button @click="show">打开弹窗</button>
  <modal name="example" height="auto">
    <p>弹窗内容</p>
    <button @click="hide">关闭</button>
  </modal>
</template>

<script>
export default {
  methods: {
    show() {
      this.$modal.show('example')
    },
    hide() {
      this.$modal.hide('example')
    }
  }
}
</script>

动态弹窗内容

通过props传递动态内容:

<Modal :title="modalTitle" :content="modalContent">
  <template v-slot:footer>
    <button @click="submit">提交</button>
  </template>
</Modal>

动画效果

添加过渡动画:

vue实现弹窗代码

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}

标签: 代码vue
分享给朋友:

相关文章

vue 实现权限

vue 实现权限

Vue 实现权限控制的方法 在 Vue 项目中实现权限控制通常涉及前端路由、组件和按钮级别的权限管理。以下是几种常见的实现方式: 路由权限控制 通过路由守卫实现权限验证,过滤用户无权访问的路由:…

vue实现颜色

vue实现颜色

Vue 实现颜色的方法 在 Vue 中实现颜色管理可以通过多种方式,以下是一些常见的方法: 使用 CSS 变量动态绑定颜色 在 Vue 组件的样式中定义 CSS 变量,并通过 Vue 的数据绑定动态…

vue实现筛选

vue实现筛选

实现筛选功能的基本思路 在Vue中实现筛选功能通常需要结合数据绑定、计算属性和方法。筛选的核心逻辑是根据用户输入的条件过滤原始数据列表,并动态更新显示结果。 数据准备 定义一个数组存储原始数据,另一…

vue实现通讯

vue实现通讯

Vue 组件通讯方法 父子组件通讯 父组件向子组件传递数据通过 props,子组件向父组件传递数据通过 $emit 事件。 父组件模板: <child-component :message=…

vue 实现赋值

vue 实现赋值

Vue 实现赋值的方法 在 Vue 中,赋值操作通常涉及数据绑定和响应式更新。以下是几种常见的赋值方式: 直接赋值给 data 属性 在 Vue 实例的 data 对象中定义的属性可以直接通过 th…

vue实现CRUD

vue实现CRUD

Vue 实现 CRUD 操作 Vue 提供了响应式数据绑定和组件化开发能力,结合后端 API 可以轻松实现 CRUD(增删改查)功能。以下是基于 Vue 3 和 Axios 的完整实现方案。 安装依…