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

news2024/9/21 0:29:21

一、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 页面

页面中添加 http-vue-loader.js 后添加组件两种方式
方式一:

// 使用httpVueLoader
Vue.use(httpVueLoader);
var vm = new Vue({
	el: "#upload-test-form",
	components: {
	    // 将组建加入组建库
	    'upload-template': 'url:'+ctx+'components/upload-template.vue',
	},
	data: {
	    ctx:ctx,
	    fromEdit:true,
	    applyForm: {
	        ywlx:"ywlx1",
	        applyNo:"123456789",
	    },
	},
});

方式二:

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",
         },
     },
 });
<!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.coloradmin.cn/o/2109414.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

运维学习————Jenkins(1)

目录 一、项目开发周期 二、jenkins的简介和作用 三、jenkins下载 1、使用war包安装 2、初始化配置 3、工作流程图 4、Jenkins安装配置maven和git maven git 5、jenkins安装插件 6、配置maven,git,jdk jdk配置 Git配置 Maven配置 四、修改tomcat的一些配置 五…

《Nginx怎么部署vue项目》

推荐学习文档 nginx https配置ssl证书实现访问https服务Nginx实现404页面的配置方法 在开始部署之前&#xff0c;我们先要准备好以下工作&#xff1a; 一个能跑通的Vue项目一个正常的、安装了nginx的服务器&#xff08;可以是本地电脑&#xff09;服务器上安装了Node.js&…

java设计模式day02--(创建型模式:工厂模式、原型模式、建造者模式)

4&#xff0c;创建型模式 4.2 工厂模式 4.2.1 概述 需求&#xff1a;设计一个咖啡店点餐系统。 设计一个咖啡类&#xff08;Coffee&#xff09;&#xff0c;并定义其两个子类&#xff08;美式咖啡【AmericanCoffee】和拿铁咖啡【LatteCoffee】&#xff09;&#xff1b;再设…

企业必看!TPM管理咨询公司挑选全攻略

TPM&#xff08;Total Productive Maintenance,全面生产维护 &#xff09;作为一种先进的生产管理模式&#xff0c;旨在通过全员参与和持续改善&#xff0c;最大化设备综合效率&#xff08;OEE&#xff09;&#xff0c;从而提升企业整体竞争力。然而&#xff0c;实施TPM并非一蹴…

基于Flink的流式计算可视化开发实践之配置->任务生成->任务部署过程

1. 引言 在我们大数据平台(XSailboat)的DataStudio模块中实现了基于Hive的业务流程开发和基于Flink的实时计算管道开发。 DataStudio是用来进行数据开发的&#xff0c;属于开发环境&#xff0c;另外还有任务运维模块&#xff0c;负责离线分析任务和实时计算任务在生产环境的部…

解决Metasploit调用Nessus报错问题

问题描述 Error while running command nessus_scan_new: undefined method []’ for nil:NilClass 解决方法 发现报错&#xff0c;经过网上查询解决方法 在Nessus服务器执行&#xff0c;下面的版本号可能有所不同&#xff0c;更加自己的情况更改&#xff0c;需要管理员身份执…

Vue2 day-01

目录 一. Vue 是什么&#xff1f; 1.1 什么是渐进式 1.2 自底向上逐层应用 二. 相关概念 2.1 为什么学习vue 2.2 库和框架区别 2.3 三大主流框架 三. vue基本使用 3.1 体验vue的使用 3.2 相关知识分析 3.3 插值表达式{{}} 3.4 vue-devtools 四. 指令 4.1 v-cloak…

深信服EasyConnect-Docker部署方式

一、项目简介 让深信服开发的非自由的 VPN 软件 EasyConnect 或 aTrust 运行在 docker 中&#xff0c;提供 socks5 和 http 代理服务和网关供宿主机连接使用。 项目地址&#xff1a; https://github.com/docker-easyconnect/docker-easyconnect 二、图形界面版 EasyConnect&…

Oceanbase 数据库审计

数据加密和访问控制可以大幅降低安全风险&#xff0c;但对于具备权限的用户&#xff0c;仍然需要记录其操作&#xff0c;以防止用户登录信息泄露&#xff0c;或者访问权限被滥用。审计功能可以加强企业对数据安全、合规等方面的要求&#xff0c;是跟踪用户行为最主要的工具。 目…

浏览器百科:网页存储篇-Session storage应用实例(九)

1.引言 在前面的文章中&#xff0c;我们详细介绍了如何在 Chrome 浏览器中打开并使用 Session storage 窗格&#xff0c;进行数据的查看、编辑和管理。作为网页存储技术的重要组成部分&#xff0c;sessionStorage在提升用户体验和数据管理能力方面发挥了重要作用。在本篇《浏览…

NAT技术-将多个内部网络设备映射到一个公共IP地址

问题&#xff1a; 今天上课的时候老师让我们在VMware填同一个子网ip 192.168.196.0&#xff0c;然后给我们的linux镜像都是同一个压缩包&#xff0c;结果我们的静态ip地址都是同一个。 192.168.196.0下面有256个ip地址&#xff0c;范围是192.168.196.0到192.168.196.255。我们…

CP-Net:用于生物细胞解析的实例感知部分分割网络|文献速递--基于深度学习的医学影像病灶分割

Title 题目 CP-Net: Instance-aware part segmentation network for biological cell parsing CP-Net&#xff1a;用于生物细胞解析的实例感知部分分割网络 01 文献速递介绍 实例分割是计算机视觉中的一个经典任务&#xff0c;用于识别图像中每个像素的对象类别&#xff0…

基于Android Studio 实现通讯录—原创

目录 一、项目演示 二、开发环境 三、项目详情 四、项目完整源码 一、项目演示 基于Android Studio 实现通讯录—原创 二、开发环境 三、项目详情 1.启动页 这段代码是一个简单的Android应用程序启动活动&#xff08;Activity&#xff09;&#xff0c;具体功能如下&#xf…

【看雪-注册安全分析报告】

前言 由于网站注册入口容易被黑客攻击&#xff0c;存在如下安全问题&#xff1a; 暴力破解密码&#xff0c;造成用户信息泄露短信盗刷的安全问题&#xff0c;影响业务及导致用户投诉带来经济损失&#xff0c;尤其是后付费客户&#xff0c;风险巨大&#xff0c;造成亏损无底洞…

学习 SSM框架 项目总结

通过指导老师发布的学习SSM框架项目&#xff0c;这次我深刻体会到了SSM整体项目之间的紧连关系。 以下是我自己学习过程中总结出来的经验。 SSM框架 配置 导入核心 spring 组件坐标 将spring相关组件坐标&#xff0c;导入到 pom 文件中 <!--spring、springMVC--><…

集成电路学习:什么是RTOS实时操作系统

RTOS&#xff1a;实时操作系统 RTOS&#xff0c;全称Real Time Operating System&#xff0c;即实时操作系统&#xff0c;是一种专为满足实时控制需求而设计的操作系统。它能够在外部事件或数据产生时&#xff0c;以足够快的速度进行处理&#xff0c;并在规定的时间内控制生产过…

UE5.3 新学到的一些性能测试合计(曼巴学习笔记)

一.简单命令行 stat FPS stat unit //增加GPU渲染时间和变量 stat unitgraph //追加了图表显示 二.查看GPU的消耗。调试GPU渲染用的高级命令 可以记录这一刻各个部分的占用情况,只能看当前的 1.在编辑器下&#xff0c;ctrlShift, 。 2.输入命令行&#xff0c;pr…

硬件-经典的TL431三端稳压管

文章目录 一&#xff1a;TL431三端稳压管1.1 器件说明1.2 电路分析1.3 把TL431设计成一个可调电压源的电路1.4 常用型号1.5 阅读手册1.6 2.5V 电压基准应用电路道友&#xff1a;努力的意义&#xff0c;不在于一定会让你取得多大的成就&#xff0c;只是让你在平凡的日子里&#…

虚幻5|知识点(1)寻找查看旋转,击打敌人后朝向主角

举例说明&#xff0c;我们想让角色一直朝着摄像头&#xff0c;我们控制角色任意位置&#xff0c;都能自行旋转都能朝向摄像头 下面是敌人一直朝向角色&#xff0c;无论主角走向哪个位置&#xff0c;敌人都能朝向主角 start是获取敌人的位置向量大小&#xff0c;Target是获取主…

【复杂系统系列(中级)】复杂系统科学的层级与不确定性方程【代码模拟】

【通俗理解】复杂系统科学的层级与不确定性方程 关键词提炼 #复杂系统科学 #层级结构 #不确定性 #上行因果 #下行因果 #初值敏感 #混沌现象 第一节&#xff1a;层级与不确定性方程的类比与核心概念【尽可能通俗】 1.1 层级与不确定性方程的类比 复杂系统科学的层级与不确定…