vue 使用elementUI组件中的图片预览功能扩展 和 批量删除功能实现

有一列显示的图片,现需要点击图片,预览该图片,使用的elementui中的previewSrcList做的图片预览,

但是测试发现,无论点击表格中的那张图片,预览的大图都是从第一张图片,开始预览;

后面通过更改每张图片绑定的图片list的顺序,解决了次问题;

首先,自己下载
vue.js和axios.js

我用了部分layUI框架的知识点
结合了elementUI的知识点

效果图在最下面最好先看看

完整代码


<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>相册信息- Layuititle>
    <link rel="stylesheet" href="../static/layui/css/layui.css">
    <link rel="stylesheet" href="../static/css/backstage.css">
    <script src="../static/js/vue.js">script>
    <script src="../static/js/axios.js">script>
    
    
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    
    <script src="https://unpkg.com/element-ui/lib/index.js">script>
    <style>
        .user-headImage{
      
            height: 300px;
            width: 300px;
            /* display: inline-block;*/
            float: left;
        }
        .user-headImage img{
      
            object-fit: cover; /*不变形、铺满*/
            width: 100%;
            height: 100%;
            border-radius: 5%;
        }
        .list{
      
            float: left;
            margin-right: 10px;
        }
       .list-right{
      
           position: absolute;
           top: 2px;
           right: 3px;
           color: #c8e1fa;
           z-index: 1;
           cursor: pointer;
       }
        .list-right-div{
      
            display: none;
        }
        .list-right-div button{
      
            border: none;
            margin-bottom: 3px;
            background-color: #c8e1fa;
            border-radius: 3px;
            cursor: pointer;
        }
        .list-right:hover .list-right-div{
      
            display: block;
        }
        .lists-value{
      
            position: absolute;
            left: 2px;
            z-index: 1;
            display: none;
        }

    style>
head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
    <div th:replace="~{own/commes :: topbar}">div>
    <div th:replace="~{own/commes :: sidebar}">div>
    <div class="layui-body" style="padding-left: 20px">
        
        <div style="margin-top: 20px;margin-bottom: 30px">
            <button type="button" data-method="addImages" class="layui-btn layui-btn-normal addIma">上传照片/视频button>
            <button type="button" @click="deleteItems" class="layui-btn layui-btn-normal">批量删除button>

        div>

        <div class="albums">
            <div class="albums-1">
                <ul style="float: left">
                   

                        <div class="lists" style="overflow: auto">

                            <p>{
    {vals}}p>
                            
                            <div class="list" v-for="item of drawerTableList" :key="item" style="position:relative;margin-bottom: 10px">
                                
                                <td><input class="lists-value" type="checkbox" v-model="vals" :value="item.id">td>

                                <div class="list-right">
                                    <span style="float: right">菜单span>
                                    <br>
                                    <div class="list-right-div">
                                        <button  type="button" value="ww" @click="setCover(item.path)">设为封面button>
                                        <br>
                                        <button  type="button" value="12" @click="delImage(item.id)">删除图片button>
                                    div>

                                div>
                                
                                
                                el-image>
                            div>

                        div>
                        
                   
                ul>
            div>
        div>
    div>

    <div th:replace="~{own/commes :: footbar}">div>

div>


<div id="addImagesDiv" class="layui-upload" style="display: none;padding: 20px 20px">
    <button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件button>
    <div class="layui-upload-list">
        <table class="layui-table">
            <thead>
            <tr>   <th>文件名th>
                <th>文件缩略图th>
                <th>大小th>
                <th>状态th>
                <th>操作th>
            tr>thead>
            <tbody id="demoList">tbody>
        table>
    div>
    <button type="button" class="layui-btn" id="testListAction">开始上传button>
div>

<script src="../static/layui/layui.js">script>
<script src="../static/js/jquery-3.3.1.js">script>

<script>

    var a = 0;
    var lists = document.getElementsByClassName("lists-value");//删除list

    var Main = {
      
        data() {
      
            return {
      
                drawerTableList:[],//照片重新排序,还有id等信息的最终在页面输出的。
                vals:[],//这是单/多选删除的照片id集合
                initData:[]//获取后台传过来的初始化数据
            }
        },
        mounted:function(){
        //这方法相当于 页面初始化
            this.initList();
        },
        methods:{
      
            initList(){
      //拿到后台数据初始化
                var that = this;
                that.drawerTableList = [];
                that.initData = [];
                axios.get("http://localhost:8770/album/queryAlbumVue")
                    .then(function (response) {
      
                        that.initData = response.data;
                        that.array();
                    },function (err) {
      
                        console.log("出错")
                    })
            },
            array(){
      //对预览图片中的list重新排序
                var that = this;
                this.list = [];
               // 表格数据  drawerTableList
               //获取每张图片的地址
               //获取每张图片的地址
                for(var i = 0 ; i < that.initData.length ; i ++){
      
                    this.list.push('/'+that.initData[i].i_path);
                }
               //根据图片顺序(index)更改每张图片绑定的list的图片顺序
               for(var i = 0 ; i < that.initData.length ; i ++){
      
                   //按当前照片index重新排序
                   var container = this.list;
                   var frontArr = container.slice(0,i);
                   var behindArr = container.slice(i,that.initData.length);
                   var list = behindArr.concat(frontArr);

                   //为数组添加属性和值
                   this.drawerTableList.push({
      id:that.initData[i].i_id,aid:that.initData[i].aid,
                       size:that.initData[i].i_size,uploadTime:that.initData[i].i_uploadTime,
                       path: this.list[i],list:list});
               }

               console.log("排序好的:");
               console.log(that.drawerTableList);

            },
            setCover(v) {
      //设置照片为相册封面
                var that = this;
                var coverPath = v;

                this.$confirm('此操作将设置照片为相册封面, 是否继续?', '提示', {
      
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(() => {
      
                    axios.get("http://localhost:8770/album/setCoverVue?coverPath="+coverPath)
                        .then(function (response) {
      

                        },function (err) {
      
                            console.log("出错")
                        });

                    this.$message({
      
                        type: 'success',
                        message: '设置成功!'
                    });
                }).catch(() => {
      
                    this.$message({
      
                        type: 'info',
                        message: '已取消设置'
                    });
                });
            },
            delImage:function (v) {
      //删除单个照片
                var that = this;
                that.vals.push(v);
                this.deleteComm(that);

            },
            deleteItems:function () {
      //点击删除按钮,判断a=0  浮现标签,a=1传入照片id集合进入后台进行多个照片删除
                var that = this;
                if (a==0){
      
                    for (var i=0;i<lists.length;i++){
      
                        lists[i].style.display='block';
                    }
                    a=1;
                }
                else{
      
                    this.deleteComm(that);
                    console.log("提交进入后台成功后");
                    for (var i=0;i<lists.length;i++){
      
                        lists[i].style.display='none';
                    }
                    a=0;
                }
            },
            deleteComm:function (that) {
        //删除照片的公共方法
                this.$confirm('此操作将删除照片, 是否继续?', '提示', {
      
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
      
                    console.log("eeee");
                    axios.get("http://localhost:8770/album/deleteItemVue?vals="+that.vals)
                        .then(function (response) {
      
                            that.vals = [];
                            //更新照片列表
                            that.initList();
                        },function (err) {
      
                            console.log("出错")
                        });
                    this.$message({
      
                        type: 'success',
                        message: '删除成功!'
                    });
                }).catch(() => {
      
                    this.$message({
      
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            }
        }
    }

    var Ctor = Vue.extend(Main);
    new Ctor().$mount('.layui-body');

script>
<script>
    //一般直接写在一个js文件中
    layui.use(['layer', 'form'], function(){
      
        var layer = layui.layer
            ,form = layui.form;
    });
    layui.use('form', function(){
      
        var form = layui.form;

        //监听提交,使用ajax提交
        form.on('submit(formDemo)', function(data){
      
            layer.msg(JSON.stringify(data.field));
            alert(JSON.stringify(data.field));
            $.ajax({
      
                type:"POST",
                dataType:"json",
                url:"/user/updatePersonDate",
                data:JSON.stringify(data.field),
                contentType:"application/json",
                success:function (result) {
      
                    /* console.log(result);*/
                },
                error:function () {
      
                    alert("异常!")
                }

            });

            return false;
        });
    });
    //JavaScript代码区域
    layui.use('element', function(){
      
        var element = layui.element;

    });
    layui.use('laydate', function(){
      
        var laydate = layui.laydate;

        //执行一个laydate实例
        laydate.render({
      
            elem: '#test1' //指定元素
        });
    });



    //弹出层:添加图片
    layui.use('layer', function() {
       //独立版的layer无需执行这一句
        var $ = layui.jquery, layer = layui.layer; //独立版的layer无需执行这一句
        //弹出层:创建相册
        //触发事件
        var active = {
      
            addImages: function () {
      
                var that = this;
                //多窗口模式,层叠置顶
                layer.open({
      
                    type: 1 //此处以iframe举例
                    , title: ['添加照片', 'font-size:18px;text-align:center;']
                    , area: ['1400px', '700px'] //宽高
                    , shade: 0
                    , content: $('#addImagesDiv')
                    , btn: ["确认", "取消"] //只是为了演示
                    , yes: function (index, layero) {
      

                        $(that).click();
                    }
                });
            }
        };

        $('.addIma').on('click', function () {
      
            var othis = $(this), method = othis.data('method');
            active[method] ? active[method].call(this, othis) : '';
            // var i = $(this).val();
        });
    });
    //上传图片
    layui.use('upload', function(){
      
        var $ = layui.jquery
            ,upload = layui.upload;

        //多文件列表示例
        var demoListView = $('#demoList')
            ,uploadListIns = upload.render({
      
            elem: '#testList'
            ,url: '/album/addImages' //改成您自己的上传接口
            ,accept: 'file'
            ,multiple: true
            ,auto: false
            ,bindAction: '#testListAction'
            ,choose: function(obj){
      
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function(index, file, result){
      
                    var tr = $(['+ index +'">'
                        ,''+ file.name +''
                        ,'+ result +'" alt="'+ file.name +'" class="layui-upload-img">'  //图片缩略图
                        ,''+ (file.size/1024).toFixed(1) +'kb'
                        ,'等待上传'
                        ,''
                        ,''
                        ,''
                        ,''
                        ,''].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function(){
      
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function(){
      
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
                    });

                    demoListView.append(tr);
                });
            }
            ,done: function(res, index, upload){
      
                if(res.success==1){
       //上传成功
                    var tr = demoListView.find('tr#upload-'+ index)
                        ,tds = tr.children();
                    tds.eq(3).html('上传成功');
                    tds.eq(4).html(''); //清空操作
                    //tr.html('');
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
            ,error: function(index, upload){
      
                var tr = demoListView.find('tr#upload-'+ index)
                    ,tds = tr.children();
                tds.eq(3).html('上传失败');
                tds.eq(4).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
        });

    });



script>
body>
html>

核心代码讲解

核心HTML

<div class="layui-layout layui-layout-admin">
    <div th:replace="~{own/commes :: topbar}">div>
    <div th:replace="~{own/commes :: sidebar}">div>
    <div class="layui-body" style="padding-left: 20px">
        
        <div style="margin-top: 20px;margin-bottom: 30px">
            <button type="button" data-method="addImages" class="layui-btn layui-btn-normal addIma">上传照片/视频button>
            <button type="button" @click="deleteItems" class="layui-btn layui-btn-normal">批量删除button>

        div>

        <div class="albums">
            <div class="albums-1">
                <ul style="float: left">
                   

                        <div class="lists" style="overflow: auto">

                            <p>{
    {vals}}p>
                            
                            <div class="list" v-for="item of drawerTableList" :key="item" style="position:relative;margin-bottom: 10px">
                                
                                <td><input class="lists-value" type="checkbox" v-model="vals" :value="item.id">td>

                                <div class="list-right">
                                    <span style="float: right">菜单span>
                                    <br>
                                    <div class="list-right-div">
                                        <button  type="button" value="ww" @click="setCover(item.path)">设为封面button>
                                        <br>
                                        <button  type="button" value="12" @click="delImage(item.id)">删除图片button>
                                    div>

                                div>
                                
                                
                                el-image>
                            div>

                        div>
                        
                   
                ul>
            div>
        div>
    div>

    <div th:replace="~{own/commes :: footbar}">div>

div>

核心css

在上面完整代码中,是直接在 style 标签中写的

核心JS

只需要看initList()方法和array()方法中的

<script>

    var a = 0;
    var lists = document.getElementsByClassName("lists-value");//删除list

    var Main = {
     
        data() {
     
            return {
     
                drawerTableList:[],//照片重新排序,还有id等信息的最终在页面输出的。
                vals:[],//这是单/多选删除的照片id集合
                initData:[]//获取后台传过来的初始化数据
            }
        },
        mounted:function(){
       //这方法相当于 页面初始化
            this.initList();
        },
        methods:{
     
            initList(){
     //拿到后台数据初始化
                var that = this;
                that.drawerTableList = [];
                that.initData = [];
                axios.get("http://localhost:8770/album/queryAlbumVue")
                    .then(function (response) {
     
                        that.initData = response.data;
                        that.array();
                    },function (err) {
     
                        console.log("出错")
                    })
            },
            array(){
     //对预览图片中的list重新排序
                var that = this;
                this.list = [];
               // 表格数据  drawerTableList
               //获取每张图片的地址
               //获取每张图片的地址
                for(var i = 0 ; i < that.initData.length ; i ++){
     
                    this.list.push('/'+that.initData[i].i_path);
                }
               //根据图片顺序(index)更改每张图片绑定的list的图片顺序
               for(var i = 0 ; i < that.initData.length ; i ++){
     
                   //按当前照片index重新排序
                   var container = this.list;
                   var frontArr = container.slice(0,i);
                   var behindArr = container.slice(i,that.initData.length);
                   var list = behindArr.concat(frontArr);

                   //为数组添加属性和值
                   this.drawerTableList.push({
     id:that.initData[i].i_id,aid:that.initData[i].aid,
                       size:that.initData[i].i_size,uploadTime:that.initData[i].i_uploadTime,
                       path: this.list[i],list:list});
               }

               console.log("排序好的:");
               console.log(that.drawerTableList);

            },
            setCover(v) {
     //设置照片为相册封面
                var that = this;
                var coverPath = v;

                this.$confirm('此操作将设置照片为相册封面, 是否继续?', '提示', {
     
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(() => {
     
                    axios.get("http://localhost:8770/album/setCoverVue?coverPath="+coverPath)
                        .then(function (response) {
     

                        },function (err) {
     
                            console.log("出错")
                        });

                    this.$message({
     
                        type: 'success',
                        message: '设置成功!'
                    });
                }).catch(() => {
     
                    this.$message({
     
                        type: 'info',
                        message: '已取消设置'
                    });
                });
            },
            delImage:function (v) {
     //删除单个照片
                var that = this;
                that.vals.push(v);
                this.deleteComm(that);

            },
            deleteItems:function () {
     //点击删除按钮,判断a=0  浮现标签,a=1传入照片id集合进入后台进行多个照片删除
                var that = this;
                if (a==0){
     
                    for (var i=0;i<lists.length;i++){
     
                        lists[i].style.display='block';
                    }
                    a=1;
                }
                else{
     
                    this.deleteComm(that);
                    console.log("提交进入后台成功后");
                    for (var i=0;i<lists.length;i++){
     
                        lists[i].style.display='none';
                    }
                    a=0;
                }
            },
            deleteComm:function (that) {
       //删除照片的公共方法
                this.$confirm('此操作将删除照片, 是否继续?', '提示', {
     
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
     
                    console.log("eeee");
                    axios.get("http://localhost:8770/album/deleteItemVue?vals="+that.vals)
                        .then(function (response) {
     
                            that.vals = [];
                            //更新照片列表
                            that.initList();
                        },function (err) {
     
                            console.log("出错")
                        });
                    this.$message({
     
                        type: 'success',
                        message: '删除成功!'
                    });
                }).catch(() => {
     
                    this.$message({
     
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            }
        }
    }

    var Ctor = Vue.extend(Main);
    new Ctor().$mount('.layui-body');

</script>
  
  //删除单/多个照片
    @GetMapping("/deleteItemVue")
    @ResponseBody
    public void deleteItem(String[] vals,HttpSession session){
      //传入照片id  用户id
        System.out.println("vals:"+ Arrays.toString(vals));
        .....
    }

效果图

vue 使用elementUI组件中的图片预览功能扩展 和 批量删除功能实现_第1张图片

点击图片,效果成功。
点击三张图片中的任意一张,都会弹出点击的图片
vue 使用elementUI组件中的图片预览功能扩展 和 批量删除功能实现_第2张图片
初始化时后台返回的参数
vue 使用elementUI组件中的图片预览功能扩展 和 批量删除功能实现_第3张图片

参考:https://blog.csdn.net/weixin_30586085/article/details/102005650

你可能感兴趣的:(elementui,vue,html,js)