帮我用vue写一个 既能预览图片又能预览视频的弹窗
这里是一个简单的代码示例,用Vue.js实现预览图片和视频的弹窗:
<template>
<div>
<button @click="showModal">打开弹窗</button>
<div v-if="isModalVisible" class="modal">
<div class="modal-content">
<div v-if="isImage">
<img :src="url" alt="图片预览">
</div>
<div v-if="isVideo">
<video :src="url" controls></video>
</div>
<button @click="closeModal">关闭弹窗</button>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isModalVisible: false,
isImage: false,
isVideo: false,
url: ''
}
},
methods: {
showModal() {
// 模拟获取图片或视频的数据
const data = {
type: 'image',
url: 'https://picsum.photos/200'
}
if (data.type === 'image') {
this.isImage = true
} else if (data.type === 'video') {
this.isVideo = true
}
this.url = data.url
this.isModalVisible = true
},
closeModal() {
this.isModalVisible = false
this.isImage = false
this.isVideo = false
this.url = ''
}
}
}
</script>
<style>
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
}
.modal-content {
background-color: #fff;
padding: 20px;
}
</style>
在这个代码示例中,我们首先定义了一个按钮,点击该按钮会触发showModal()方法,弹出一个模态框。模态框包含一个<div>元素,其中根据当前预览内容的类型(图片或视频),分别渲染了<img>或<video>元素。关闭模态框的按钮通过closeModal()方法实现。
我们通过data()函数初始化了一些状态,包括模态框是否可见、预览内容的类型、以及内容的URL地址。在showModal()方法中,我们模拟获取预览数据的过程,并根据数据类型设置了模态框的内容。在关闭模态框时,我们需要重置所有状态。
最后,我们为模态框和内容的样式添加了一些基本的CSS,以确保它们在屏幕中央居中显示,并具有一定的美观性。
原文地址: http://www.cveoy.top/t/topic/bWdx 著作权归作者所有。请勿转载和采集!