html 页面引入 vue 组件之 http-vue-loader.js

一、http-vue-loader.js

           http-vue-loader.js 是一个 Vue 单文件组件加载器,可以让我们在传统的 HTML 页面中使用 Vue 单文件组件,而不必依赖 Node.js 等其他构建工具。它内置了 Vue.js 和样式加载器,并能自动解析 Vue 单文件组件中的所有内容,并将其转化为 JavaScript 代码。

ps :注意:httpVueLoader 加载的单文件导出方式不同:module.exports = {},而不是 export default {}

二、示例

这里对了 elementUI 的上传组件做一个封装,使其能可根据业务来配置上传的附件

2.1. vue 组件

<template>
  <div>
    <el-col :span="24" v-for="(template,index) in uploadsTemplates">
      <el-card style="margin-top: 20px;">
        <div slot="header" class="clearfix">
          <el-row style="display: flex;align-items: center;">
            <el-col :span="20"><span style="font-size: 16px;">{{template.title}}</span></el-col>
            <el-col :span="4" style="text-align: right;">
              <el-tag v-if="template.required == 'N'" type="info">非必上传</el-tag>
              <el-tag v-if="template.required == 'Y'" type="danger">必须上传</el-tag>
            </el-col>
          </el-row>
        </div>
        <p style="color: #F56C6C;margin-bottom: 5px;">
          {{template.description}}
        </p>
        <el-col :span="12" style="padding: 20px 0 ">
          <el-form-item prop="requiredFile"
                        ref="uploadFormItems"
                        :rules="template.success||template.required=='N'?[]:[{required: true, message: '请上传必要件', trigger: 'blur'}]">
            <el-row>
              <el-upload :auto-upload="true"
                         drag
                         :file-list="template.fileList"
                         ref="uploadComponents"
                         name="attachment"
                         :on-preview="(file)=>onPreview(file,template)"
                         :before-upload="(file)=>onBeforeUpload(file,template)"
                         :on-success="(response,file,fileList)=>onUploadSuccess(response,file,fileList,index)"
                         :on-remove="(file,fileList)=>onRemoveFile(file,fileList,index,template)"
                         :action="uploadsUrl"
                         :data="{ywlx:ywlx,applyNo:applyNo,configId:template.configId}"
                         multiple>
                <i class="el-icon-upload"></i>
                <div>将文件拖到此处,或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">{{msg}}</div>
              </el-upload>
            </el-row>
          </el-form-item>
        </el-col>

      </el-card>
    </el-col>
    <div class="demo-image__preview" style="display: none">
      <el-image
                style="width: 100px; height: 100px"
                ref="imagePreview"
                :src="previewSrc"
                :preview-src-list="previewSrcList">
      </el-image>
    </div>
  </div>
</template>

<script>
module.exports = {
  name: "upload-template",
  props: ['contextPath', 'applyNo', 'ywlx', 'fromedit','msg','beforeUpload'],
  data() {
    return {
      uploadsUrl: this.contextPath + "/system/sysUploadFile/uploadAttachment",
      //预览图片弹窗
      imgDialogVisible: false,
      //预览图片路径
      previewSrc: '',
      //预览图片集合
      previewSrcList: [],
      // 要件(只是校验用)
      requiredFile: [],
      //上传模板
      uploadsTemplates: [],
      //上传前钩子
      onBeforeUpload: this.beforeUpload
    }
  },
  mounted: function () {
    if(this.onBeforeUpload == null){
      this.onBeforeUpload = (file,upload)=>{
        return true;
      }
    }else{
      if (typeof this.onBeforeUpload === 'function') {

      } else {
        throw new Error('beforeUpload is not a function');
      }
    }
    // 读取附件模板
    $.ajax({
      type: "get",
      async: false,
      url: this.contextPath + '/system/sysUploadConfig/getUploadsTemplates',
      data: {ywlx: this.ywlx},
      dataType: "json"
    }).then((response) => {
      if (response.code == 0) {
        response.data.forEach(template => {
          template.success = false;
          template.fileList = [];
        });
        this.uploadsTemplates.push(...response.data);
        if (this.fromedit) {
          $.ajax({
            type: "post",
            async: false,
            url: this.contextPath + "/system/sysUploadFile/getFilesByApplyNo",
            dataType: "json",
            data: {ywlx:this.ywlx,applyNo: this.applyNo}
          }).then((response) => {
            if (response.code == 0) {
              response.data.forEach(attachemnt => {
                this.uploadsTemplates.forEach(template => {
                  if (attachemnt.configId === template.configId) {
                    template.fileList.push(attachemnt);
                    template.success = true;
                  }
                })
              });
            } else {
              this.$message({
                showClose: true,
                message: response.msg,
                type: 'error',
                offset: 200,
                duration: 10000
              });
              console.log("error:");
              console.log(response);
            }
          });
        }
      } else {
        this.$message({
          showClose: true,
          message: response.msg,
          type: 'error',
          offset: 200,
          duration: 10000
        });
        console.log("error:");
        console.log(response);
      }
    });

  },
  methods: {
    //预览图片
    onPreview: function (file, template) {
      this.previewSrc = this.contextPath+(file.url?file.url:file.response.data.url);
      template.fileList.forEach((file)=>{
        this.previewSrcList.push(this.contextPath+(file.url?file.url:file.response.data.url));
      });
      console.log(this.previewSrc)
      console.log(this.previewSrcList)
      this.$refs.imagePreview.clickHandler();
    },

    //文件上传成功的回调
    onUploadSuccess: function (response, file, fileList, index) {
      console.log('上传成功需要操作请增加事件:upload-success')
      if (response.code == 0) {
        // 把要件列表中的当前这个要件的success置为true
        this.uploadsTemplates[index].success = true;
        this.uploadsTemplates[index].fileList = fileList;
      }else {
        this.$message({
          showClose: true,
          message: response.msg,
          type: 'error',
          offset: 200,
          duration: 2000
        });
        //删除控件里某个文件
        fileList.splice(fileList.indexOf(file),1);
      }
      this.$emit('upload-success',response)

      //清除控件里所有文件
      // this.$refs.uploadComponents[index].clearFiles();
    },
    //移除某个文件
    onRemoveFile: function (file, fileList, index, upload) {
      //调用远程移除附件,传递file.fileId
      $.ajax({
        url: this.contextPath + '/system/sysUploadFile/removeAttachment',
        method: 'post',
        async: false,
        data: {fileId: file.fileId?file.fileId:file.response.data.fileId}
      }).then((response) => {
        if (response.code == 0) {
          this.uploadsTemplates[index].fileList = fileList;
          // 如果已经全部移除,加上校验
          if(fileList.length===0){
            this.uploadsTemplates[index].success = false;
          }
        } else {
          console.log("error message:");
          console.log(response.data);
          this.$message({
            showClose: true,
            message: response.msg,
            type: 'error',
            offset: 200,
            duration: 2000
          });
        }

      });
    },


  },
}
</script>

<style scoped>
  .el-upload__input{
    display: none;
  }
</style>

2.2. html 页面

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增上传文件信息')" />
    <th:block th:include="include :: element-ui('新增上传文件信息')" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content" id="upload-test-form">
        <div class="row">
            <el-form  ref="uploadForm" id="uploadForm" :model="applyForm">
                <upload-template :apply-no="applyForm.applyNo"
                                 :context-path="ctx"
                                 :before-upload="beforeUpload"
                                 @upload-success="uploadSuccess"
                                 ywlx="ywlx1"></upload-template>
            </el-form>
        </div>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: element-ui-js" />
    <script th:src="@{/lib/http-vue-loader.js}"></script>
    <script th:inline="javascript">
        var prefix = ctx + "system/sysUploadFile";
        var vm = new Vue({
            el: "#upload-test-form",
            components: {
                // 将组建加入组建库
                'upload-template': httpVueLoader(ctx+'components/upload-template.vue'),
            },
            data: {
                ctx:ctx,
                applyForm: {
                    ywlx:"ywlx1",
                    applyNo:"123456789",
                },
            },

            methods: {
                beforeUpload: function(file,template){
                    console.log("上传前操作")
                    console.log(file)
                    console.log(template)
                    //返回 true,继续上传,返回false,终止上传
                    return false;
                },
                uploadSuccess: function(file){
                    console.log("上传成功操作")
                    console.log(file)
                }
            }
        });

        function submitHandler() {
            vm.$refs.uploadForm.validate((valid) => {
                if (valid) {
                    alert('文件验证通过!');
                } else {
                    alert('文件验证失败!');
                }
            });
        }
    </script>
</body>
</html>

3.3. 效果

业务类型上传文件配置
在这里插入图片描述
业务上传附件页面
在这里插入图片描述
保存的文件
在这里插入图片描述

总结:
通过 http-vue-loader.js,我们可以在普通的 HTML 页面中使用 Vue 单文件组件来实现前端开发的快速迭代。在使用 http-vue-loader.js 时,我们需要引入 Vue.js 和 http-vue-loader.js,并使用 httpVueLoader () 方法加载 Vue 单文件组件,并将其实例化为 Vue 对象。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/872308.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

电脑知识:如何恢复 Word、媒体和存档文件?

如果您是 Word 用户&#xff0c;那么您一定对无法打开 Word 文档的问题很熟悉。当文档包含大量关键信息时&#xff0c;情况会变得更加复杂。如果您遇到这种情况&#xff0c;那么您将如何处理&#xff1f; 我们再怎么强调在外部存储位置&#xff08;如外部硬盘、网络位置&#…

jenkins 工具使用

使用方式 替代手动&#xff0c;自动化拉取、集成、构建、测试&#xff1b;是CI/CD持续集成、持续部署主流开发模式中重要的环节&#xff1b;必须组件 jenkins-gitlab&#xff0c;代码公共仓库服务器&#xff08;至少6G内存&#xff09;&#xff1b;jenkins-server&#xff0c;…

flutter Image

Flutter中&#xff0c;Image是一个用于显示图片的控件&#xff0c;可以显示网络图片、本地图片以及Asset中的图片。Image控件支持多种常见的图片格式&#xff0c;例如PNG、JPEG、GIF等。 const Image({super.key,required this.image,this.frameBuilder,this.loadingBuilder,th…

社区电商系统源码之卷轴模式:商业模式分析

随着互联网技术的发展&#xff0c;电商平台的竞争日益激烈&#xff0c;如何留住用户并提升用户粘性成为了各大电商平台关注的重点。卷轴模式作为一种新兴的用户参与和激励机制&#xff0c;在社区电商系统中得到了广泛的应用。本文将从技术角度探讨卷轴模式在社区电商系统中的实…

数据分析:R语言计算XGBoost线性回归模型的SHAP值

禁止商业或二改转载,仅供自学使用,侵权必究,如需截取部分内容请后台联系作者! 文章目录 介绍SHAP用途计算方法:应用加载R包导入数据数据预处理函数模型介绍 SHAP(SHapley Additive exPlanations)值是一种解释机器学习模型预测的方法。它基于博弈论中的Shapley值概念,…

第10讲 后端2

主要目标&#xff1a;理解滑动窗口法、位姿图优化、带IMU紧耦合的优化、掌握g2o位姿图。 第9讲介绍了以为BA为主的图优化。BA能精确优化每个相机位姿与特征点位置。不过在更大的场景中&#xff0c;大量特征点的存在会严重降低计算效率&#xff0c;导致计算量越来越大&#xff0…

3.8 串操作指令

&#x1f393; 微机原理考点专栏&#xff08;通篇免费&#xff09; 欢迎来到我的微机原理专栏&#xff01;我将帮助你在最短时间内掌握微机原理的核心内容&#xff0c;为你的考研或期末考试保驾护航。 为什么选择我的视频&#xff1f; 全程考点讲解&#xff1a;每一节视频都…

2024 高教社杯 数学建模国赛 (C题)深度剖析|农作物的种植策略|数学建模完整代码+建模过程全解全析

当大家面临着复杂的数学建模问题时&#xff0c;你是否曾经感到茫然无措&#xff1f;作为2022年美国大学生数学建模比赛的O奖得主&#xff0c;我为大家提供了一套优秀的解题思路&#xff0c;让你轻松应对各种难题&#xff01; CS团队倾注了大量时间和心血&#xff0c;深入挖掘解…

ChauffeurNet:通过模仿最佳驾驶和合成最坏情况进行学习驾驶

ChauffeurNet: Learning to Drive by Imitating the Best and Synthesizing the Worst ChauffeurNet&#xff1a;通过模仿最佳驾驶和合成最坏情况进行学习驾驶 https://arxiv.org/abs/1812.03079 Abstract Our goal is to train a policy for autonomous driving via imit…

4000字三合一!Stata、SPSS、MATLAB实现多元线性回归详解!

参加数学建模的小伙伴要注意了&#xff1a;多元线性回归几乎是所有分析方式里面最核心、最常用、最全面的模型&#xff0c;博主本科大致参加了10次数模&#xff0c;还有一次正大杯市场调研赛&#xff0c;其中获得拿得出手的奖有9次&#xff0c;有5次都用到了多元线性回归——至…

分享7款实现社会实践报告AI生成论文网站

在当今社会&#xff0c;AI技术的快速发展极大地改变了我们的生活方式和工作方式。特别是在学术研究和写作领域&#xff0c;AI工具的应用已经变得越来越普遍。本文将详细介绍7款实现社会实践报告AI生成的论文网站&#xff0c;并重点推荐千笔-AIPassPaper。 1. 千笔-AIPassPaper…

Flink 1.14.*中flatMap,filter等基本转换函数源码

这里以flatMap&#xff0c;filter为例&#xff0c;介绍Flink如果要实现这些基本转换需要实现哪些接口&#xff0c;Flink运行时调用这些实现类的入口&#xff0c;这些基本转换函数之间的类关系 一、创建基本转换函数需要实现类继承AbstractRichFunction并实现特性接口1、RichFla…

批量为某跟空间下的pod添加env(例如标签)

1、修改kube-apiserver配置文件&#xff0c;添加PodNodeSelector参数&#xff1a; –enable-admission-pluginsPodNodeSelector # 多个参数&#xff0c;则用逗号隔开systemctl daemon-reload systemctl restart kube-apiserver 2、修改指定命名空间内容&#xff1a; kubec…

SprinBoot+Vue校园活动报名微信小程序的设计与实现

目录 1 项目介绍2 项目截图3 核心代码3.1 Controller3.2 Service3.3 Dao3.4 application.yml3.5 SpringbootApplication3.5 Vue3.6 uniapp代码 4 数据库表设计5 文档参考6 计算机毕设选题推荐7 源码获取 1 项目介绍 博主个人介绍&#xff1a;CSDN认证博客专家&#xff0c;CSDN平…

C# NX二次开发-获取体全部面

使用 UF_MODL_ask_body_faces 或获取一个体的全部面&#xff1a; 代码&#xff1a; theUf.Modl.AskBodyFaces(body.Tag, out var face_list);face_list.Foreach(x > x.NxListing()); 免责声明&#xff1a; 只用于参考&#xff0c;如果有什么问题不要找我呀。

Web开发的艺术:C#开发中实现代码简洁性与规范性的终极指南

一、变量的要求 变量名 1.简短有意义: 合适: student_count&#xff0c;student_ids&#xff0c;student_enable_list, water_price 不合适: numberOfItemsInTheCart, totalPriceOfTheOrderInTheShoppingCart,temp, data,list 2.变量名之间不要太像: 合适: totalAmount, disc…

NetSuite AI 图生代码

去年的ChatGPT热潮期间&#xff0c;我们写过一篇文章说GTP辅助编程的事。 NetSuite GPT的辅助编程实践_如何打开netsuite: html script notes的视图-CSDN博客文章浏览阅读2.2k次&#xff0c;点赞4次&#xff0c;收藏3次。作为GPT综合症的一种表现&#xff0c;我们今朝来探究下…

Kettle 锁表原因及解决办法【源码级分析】

文章目录 背景源码分析锁表场景1:资源库锁表锁表场景2:写日志锁表在哪里配置的kettle_log_table?官方解释自增 SQL 获取 BatchI 原理解决自增 SQL 获取 BatchID背景 Kettle 7.1.0 经常出现锁表的情况,体现为在数据库里有一条锁表 SQL,然后整个 Kettle 都无法运行。😂�…

【Python】简单的数据类型——int、float、bool、str

目录 1. 整数类型 int 2. 浮点数类型 float 3. 布尔类型 bool 4. 字符串 str 5. 类型转换 5.1 隐式类型转换 5.2 显示类型转换 6. 输出 6.1 print函数 6.2 格式化输出 7. 输入 1. 整数类型 int a 10 print(type(a)) print(type(-2))<class int> <class i…

HBase 部署及shell操作

HBase 数据库 一、HBase 概述1.1 HBase 是什么HBase 的特点 二、HBase 模型及架构2.1 HBase 逻辑模型2.2 HBase 数据模型2.3 HBase 物理模型2.3.1 列簇物理模型2.3.2 Rowkey 字段排序2.3.3 Region 存储到不同节点2.3.4 Region 结构 2.4 HBase 基本架构 三、搭建 HBase 分布式集…