Vueweb 前端vue

element-ui 实战各种小技巧(长期更新)

2018-06-04  本文已影响222人  sunxiaochuan

资料

element-ui 中文官网
element-ui 官网组件使用指南

1. 项目中安装并引用 element-ui

官网安装地址
官网引入地址
因为是初次使用,所以我这里先全部引用,并没有使用官网下面介绍的按需引用的方法

npm i element-ui -S
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

Vue.use(ElementUI)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  render: h => h(App)
})

image.png

2. 解决一个页面多个 Upload 组件,出现 "上传成功之后无法判断是哪个组件" 的问题

官网地址

image.png
image.png

给【选取文件】这个按钮绑了个点击事件 ,多用了个变量 uploadSign 做标记 成功的时候判断标记 uploadSign 相应的值就好了

<template>
  <div>
    <el-form>
      <el-form-item label="身份证正面">
        <el-row :gutter="30">
          <el-col :span="8">
            <div class="grid-content">
              <el-upload
                class="upload-demo"
                ref="frontPic"
                accept="image/png, image/jpeg"
                name="imgPath"
                :action="imgUploadAPI"
                :before-upload="beforeAvatarUpload"
                :on-success="handleSuccess"
                :limit="1"
                :on-exceed="handleExceed"
                list-type="picture">
                <el-button size="small" type="primary" @click="uploadSign=1">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
              </el-upload>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content">
              <img class="show-img" src="@/assets/img/frontPic.png" alt="样图" />
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="身份证背面">
        <el-row :gutter="30">
          <el-col :span="8">
            <div class="grid-content">
              <el-upload
                class="upload-demo"
                ref="reversePic"
                accept="image/png, image/jpeg"
                name="imgPath"
                :action="imgUploadAPI"
                :before-upload="beforeAvatarUpload"
                :on-success="handleSuccess"
                :limit="1"
                :on-exceed="handleExceed"
                list-type="picture">
                <el-button size="small" type="primary" @click="uploadSign=2">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
              </el-upload>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content">
              <img class="show-img" src="@/assets/img/reversePic.png" alt="样图" />
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="身份证SIM卡手持">
        <el-row :gutter="30">
          <el-col :span="8">
            <div class="grid-content">
              <el-upload
                class="upload-demo"
                ref="handPic"
                accept="image/png, image/jpeg"
                name="imgPath"
                :action="imgUploadAPI"
                :before-upload="beforeAvatarUpload"
                :on-success="handleSuccess"
                :limit="1"
                :on-exceed="handleExceed"
                list-type="picture">
                <el-button size="small" type="primary" @click="uploadSign=3">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
              </el-upload>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content">
              <img class="show-img" src="@/assets/img/handPic.png" alt="样图" />
            </div>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import qs from 'qs' // 解决 axios 数据提交格式与后台不一致的问题  -> name=hehe&age=10
import { Loading } from 'element-ui'

export default {
  name: 'App',
  data() {
    return {
      // 多个上传组件标记  1 身份证正面;2 身份证背面;3 省份证SIM卡手持
      uploadSign: null,
      // 图片上传接口
      imgUploadAPI: '/jjhServerApi/ab/imgPath',
      // 信息提交接口
      postAPI: '/jjhServerApi/ab/insertposn',
      // 信息提交数据
      postData: {
        /**
         * name 姓名
         * department 部门
         * phoneNumber 手机号码
         * position 职位
         * certCode 证件号  身份证号
         * companyId 公司Id
         * frontPic 身份证正面
         * reversePic 身份证反面
         * handPic 手持身份证
         * lastOperation 该记录最后操作   A:添加操作,D:设置为离职操作
         */
        name: '',
        phoneNumber: '',
        department: '',
        position: '',
        certCode: '',
        companyId: '1', // 先写一个假数据
        frontPic: '',
        reversePic: '',
        handPic: '',
        lastOperation: 'A'
      }
  },
  methods: {
    // 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。
    // 判断上传文件类型
    beforeAvatarUpload: function(file) {
      const me = this
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      if (!(isJPG || isPNG)) {
        me.$message.error('上传的文件只能是 JPG 或者是 PNG 格式的')
      }
    },
    // 文件超出个数限制时的钩子
    handleExceed(file, fileList) {
      const me = this
      me.$message.warning('只能上传一个文件')
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file) {
      const me = this
      const sign = me.uploadSign
      // 判断 code 是否为  0    0 代表成功
      if (res.code === 0) {
        // 通过 sign 判断给相应的字段赋值
        if (sign === 1) {
          // 正面
          me.postData.frontPic = JSON.parse(res.result).url
        } else if (sign === 2) {
          // 背面
          me.postData.reversePic = JSON.parse(res.result).url
        } else if (sign === 3) {
          // 手持
          me.postData.handPic = JSON.parse(res.result).url
        }
      } else {
        // 失败回调
        me.$message.error(`${res.info}`)
        // 通过 sign 判断清空相应的列表 因为默认会显示出图片其实是失败了,容易造成用户误解
        if (sign === 1) {
          // 正面
          me.$refs.frontPic.clearFiles()
        } else if (sign === 2) {
          // 背面
          me.$refs.reversePic.clearFiles()
        } else if (sign === 3) {
          // 手持
          me.$refs.handPic.clearFiles()
        }
      }
      // 清空标记
      me.uploadSign = null
    }
  }
}
</script>
Animation49.gif

3. form 表单验证规则

官网地址

Animation50.gif
<template>
  <div class="container">
    <el-form ref="dataForm" :model="postData" :rules="rules" label-width="180px">
      <el-form-item label="员工姓名" prop="name">
        <el-input v-model="postData.name" type="text" placeholder="请输入员工姓名" autofocus=""></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input v-model="postData.phoneNumber" type="text" placeholder="请输入手机号码"></el-input>
      </el-form-item>
      <el-form-item label="部门" prop="department">
        <el-select v-model="postData.department" placeholder="请选择部门">
          <el-option label="管理层" value="管理层"></el-option>
          <el-option label="研发部" value="研发部"></el-option>
          <el-option label="市场部" value="市场部"></el-option>
          <el-option label="行政部" value="行政部"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="职位" prop="position">
        <el-input v-model="postData.position" type="text" placeholder="请输入职位"></el-input>
      </el-form-item>
      <el-form-item label="身份证号" prop="certCode">
        <el-input v-model="postData.certCode" type="text" placeholder="请输入身份证号"></el-input>
      </el-form-item>
      <el-form-item label="身份证正面">
        <el-row :gutter="30">
          <el-col :span="11">
            <div class="grid-content">
              <el-upload
                class="upload-demo"
                ref="frontPic"
                accept="image/png, image/jpeg"
                name="imgPath"
                :action="imgUploadAPI"
                :before-upload="beforeAvatarUpload"
                :on-success="handleSuccess"
                :before-remove="beforeRemove"
                :on-remove="handleRemoveFront"
                :limit="1"
                :on-exceed="handleExceed"
                list-type="picture">
                <el-button size="small" type="primary" @click="uploadSign=1">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
              </el-upload>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content">
              <img class="show-img" src="@/assets/img/frontPic.png" alt="样图" />
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="身份证背面">
        <el-row :gutter="30">
          <el-col :span="11">
            <div class="grid-content">
              <el-upload
                class="upload-demo"
                ref="reversePic"
                accept="image/png, image/jpeg"
                name="imgPath"
                :action="imgUploadAPI"
                :before-upload="beforeAvatarUpload"
                :on-success="handleSuccess"
                :before-remove="beforeRemove"
                :on-remove="handleRemoveReverse"
                :limit="1"
                :on-exceed="handleExceed"
                list-type="picture">
                <el-button size="small" type="primary" @click="uploadSign=2">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
              </el-upload>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content">
              <img class="show-img" src="@/assets/img/reversePic.png" alt="样图" />
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="身份证SIM卡手持">
        <el-row :gutter="30">
          <el-col :span="11">
            <div class="grid-content">
              <el-upload
                class="upload-demo"
                ref="handPic"
                accept="image/png, image/jpeg"
                name="imgPath"
                :action="imgUploadAPI"
                :before-upload="beforeAvatarUpload"
                :on-success="handleSuccess"
                :before-remove="beforeRemove"
                :on-remove="handleRemoveHand"
                :limit="1"
                :on-exceed="handleExceed"
                list-type="picture">
                <el-button size="small" type="primary" @click="uploadSign=3">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
              </el-upload>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content">
              <img class="show-img" src="@/assets/img/handPic.png" alt="样图" />
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('dataForm')">立即提交</el-button>
    <el-button @click="resetForm('dataForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import qs from 'qs' // 解决 axios 数据提交格式与后台不一致的问题  -> name=hehe&age=10
import { Loading } from 'element-ui'

export default {
  name: 'App',
  data() {
    return {
      // 多个上传组件标记  1 身份证正面;2 身份证背面;3 省份证SIM卡手持
      uploadSign: null,
      // 图片上传接口
      imgUploadAPI: '/jjhServerApi/ab/imgPath',
      // 信息提交接口
      postAPI: '/jjhServerApi/ab/insertposn',
      // 信息提交数据
      postData: {
        /**
         * name 姓名
         * department 部门
         * phoneNumber 手机号码
         * position 职位
         * certCode 证件号  身份证号
         * companyId 公司Id
         * frontPic 身份证正面
         * reversePic 身份证反面
         * handPic 手持身份证
         * lastOperation 该记录最后操作   A:添加操作,D:设置为离职操作
         */
        name: '',
        phoneNumber: '',
        department: '',
        position: '',
        certCode: '',
        companyId: '1', // 先写一个假数据
        frontPic: '',
        reversePic: '',
        handPic: '',
        lastOperation: 'A'
      },
      // 表单定义验证规则   trigger 为触发条件 http://element-cn.eleme.io/#/zh-CN/component/form#biao-dan-yan-zheng   官网地址
      rules: {
        // 姓名
        name: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
        // 手机号码
        phoneNumber: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: function(rule, value, callback) {
              var MobileRegex = /^(13[0-9]|147|15[0-9]|17[0-9]|18[0-9])\d{8}$/
              if (!MobileRegex.test(value)) {
                callback(new Error('手机号码格式不正确!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        // 选择部门
        department: [
          {
            required: true,
            message: '请选择您的部门',
            trigger: 'change'
          }
        ],
        // 职位
        position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
        // 身份证号
        certCode: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          {
            validator: function(rule, value, callback) {
              var MobileRegex = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/
              if (!MobileRegex.test(value)) {
                callback(new Error('身份证号格式不正确!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。
    beforeAvatarUpload: function(file) {
      // 判断上传文件类型
      const me = this
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      if (!(isJPG || isPNG)) {
        me.$message.error('上传的文件只能是 JPG 或者是 PNG 格式的')
      }
    },
    // 文件超出个数限制时的钩子
    handleExceed(file, fileList) {
      const me = this
      me.$message.warning('只能上传一个文件')
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file) {
      const me = this
      const sign = me.uploadSign
      // 判断接口返回的 code 是否为  0    0 代表成功
      if (res.code === 0) {
        // 通过 sign 判断给相应的字段赋值
        if (sign === 1) {
          // 正面
          me.postData.frontPic = JSON.parse(res.result).url
        } else if (sign === 2) {
          // 背面
          me.postData.reversePic = JSON.parse(res.result).url
        } else if (sign === 3) {
          // 手持
          me.postData.handPic = JSON.parse(res.result).url
        }
      } else {
        // 失败回调
        me.$message.error(`${res.info}`)
        // 通过 sign 判断清空相应的列表 因为默认会显示出图片其实是失败了,容易造成用户误解
        if (sign === 1) {
          // 正面
          me.$refs.frontPic.clearFiles()
        } else if (sign === 2) {
          // 背面
          me.$refs.reversePic.clearFiles()
        } else if (sign === 3) {
          // 手持
          me.$refs.handPic.clearFiles()
        }
      }
      // 清空标记
      me.uploadSign = null
    },
    // 删除文件之前的钩子,参数为上传的文件和文件列表,若返回 false 或者返回 Promise 且被 reject,则停止上传。
    beforeRemove(file, fileList) {
      // 增加一个询问框
      return this.$confirm(`确定移除 ${file.name}?`)
    },
    // 文件列表移除文件时的钩子 因为是三个组件所以便分开写了三个方法,写成一个带参数的试过了不行
    handleRemoveFront(file, fileList) {
      const me = this
      me.postData.frontPic = ''
    },
    handleRemoveReverse(file, fileList) {
      const me = this
      me.postData.reversePic = ''
    },
    handleRemoveHand(file, fileList) {
      const me = this
      me.postData.handPic = ''
    },
    // 提交数据
    submitForm(formName) {
      const me = this
      this.$refs[formName].validate(valid => {
        // 通过插件自定义全部规则已验证通过
        if (valid) {
          if (!me.postData.frontPic) {
            me.$message.error('请上传您的身份证正面图片')
            return false
          }
          if (!me.postData.reversePic) {
            me.$message.error('请上传您的身份证反面图片')
            return false
          }
          if (!me.postData.handPic) {
            me.$message.error('请上传您的身份证SIM卡手持图片')
            return false
          }
          let loading = Loading.service({
            fullscreen: true,
            text: '正在请求服务器'
          })
          me.axios
            .post(me.postAPI, qs.stringify(me.postData))
            .then(response => {
              loading.close()
              const getData = response.data
              // code 为 0 表示成功
              if (getData.code === 0) {
                me.$message.success(`${getData.info},即将自动跳转至列表页面`)
                // 新增成功跳转至 【通讯录管理】页面
                setTimeout(function() {
                  location.href = 'addresslist.html'
                }, 2000)
              } else {
                me.$message.error(getData.info)
              }
            })
            .catch(error => {
              console.log(error)
              me.$message.error('请求服务器失败了,请稍后重试!')
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 重置表单
    resetForm(formName) {
      const me = this
      this.$refs[formName].resetFields()
      // 清空上传的文件
      // 正面
      me.$refs.frontPic.clearFiles()
      // 背面
      me.$refs.reversePic.clearFiles()
      // 手持
      me.$refs.handPic.clearFiles()
      me.postData.frontPic = ''
      me.postData.reversePic = ''
      me.postData.handPic = ''
    }
  }
}
</script>

<style lang="less">
body {
  .container {
    form {
      width: 700px;
      margin: 0 auto;
      .show-img {
        width: 300px;
        max-width: 100%;
      }
    }
  }
}
</style>

Animation51.gif
// 三个上传字段写个数组方便下面使用,就不用一个一个的判断 uploadSign 的值了,直接 me.postData[me.uploadSignString[me.uploadSign]] 即可
      uploadSignString: ['frontPic', 'reversePic', 'handPic'],

// 通过 [me.uploadSignString[me.uploadSign]] 判断给相应的字段赋值
        me.postData[me.uploadSignString[me.uploadSign]] = JSON.parse(
          res.result
        ).url

// 通过 sign 判断清空相应的列表 因为默认会显示出图片其实是失败了,容易造成用户误解
        me.$refs[me.uploadSignString[me.uploadSign]].clearFiles()
image.png
image.png
上一篇下一篇

猜你喜欢

热点阅读