Vue3 + Element Plus 常用代码片段

收录 Vue3 与 Element Plus 开发中的常用代码片段,包括 el-table 序号、el-upload 图片上传、动态表单校验、flv.js 视频播放等。
AI 迁移提示

本文由 AI 协助从旧站迁移,尚未完成逐篇人工审校;内容如有疏漏,将在复核后修订。

一、el-table 添加序号

el-table 中添加从 1 开始的序号列,支持分页连续编号。

template:

html
<el-table-column label="序号" align="center" type="index" :index="indexMethod"/>

script:

js
indexMethod(index) {
  let pageNum = this.queryParams.pageNum - 1;
  if ((pageNum !== -1 && pageNum !== 0)) {
    return (index + 1) + (pageNum * this.queryParams.pageSize);
  } else {
    return (index + 1)
  }
},

二、el-upload 上传图片

使用 el-upload 组件实现图片上传、格式校验与回显。

template:

html
<el-form-item label="现场照片" prop="urls">
  <el-upload
    v-model:file-list="imgFileList1"
    :action="action"
    :headers="imgToken"
    :on-success="handleSuccess1"
    list-type="picture-card"
    :before-upload="beforeAvatarUpload"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove1"
  >
    <el-icon>
      <Plus />
    </el-icon>
  </el-upload>
</el-form-item>

data:

js
imgFileList1: [],
imgFileListForm: [],
piclist1: [],
imgToken: {
  'Blade-Auth': 'Bearer ' + JSON.parse(localStorage.getItem('saber-token')).content
},
limitImg: 10,
action: `/api/blade-resource/oss/endpoint/put-file`,
disabled: false,
dialogImageUrl: '',
dialogVisible: false

methods:

js
beforeAvatarUpload(file) {
  const imgType = file.type === 'image/jpeg' || file.type === 'image/png';
  const imgSize = file.size / 1024 / 1024 < 5;
  if (!imgType) {
    this.$utils.toast('图片只能是 JPG/PNG 格式!', 'error');
  }
  if (!imgSize) {
    this.$utils.toast('图片大小不能超过 5MB!', 'error');
  }
  return imgType && imgSize;
},

handlePictureCardPreview(uploadFile) {
  this.dialogImageUrl = uploadFile.url;
  this.dialogVisible = true;
},

handleRemove1(res) {
  let index = this.imgFileListForm.findIndex(e => e === res.url);
  this.imgFileListForm.splice(index, 1);
},

handleSuccess1(res) {
  if (res.code === 200) {
    this.imgFileListForm.push(res.data.link);
  }
},

图片回显:

js
if (this.form.images) {
  this.form.images.forEach(value => {
    this.imgFileList1.push({ url: value });
  });
}

三、动态添加输入框并校验

利用 Vue3 响应式能力,在 el-table 中动态添加输入框并实现实时校验。

四、flv.js 播放 FLV 视频流

在 Vue3 中使用 flv.js 播放 HTTP-FLV 在线视频流。

bash
npm install vue flv.js --save
Chrome硬件加速功能开启与关闭
2023的某一天

评论区

评论加载中...