vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue.js element-ui表单

vue.js+element-ui的基础表单实例代码

作者:流情

这篇文章主要介绍了vue.js+element-ui的基础表单实例代码,技术栈即html+vue.js+element-ui,而使用它们的方法也很简单,引入对应的js和css文件即可,需要的朋友可以参考下

遇到原生的html小型单页应用时,是脱离了vue框架,而我们又想使用vue的语法和element的组件加快我们的开发速度,这个时候就需要引用他们的js了。技术栈即html+vue.js+element-ui。而使用它们的方法也很简单,引入对应的js和css文件即可。下面用一个小例子展示下。

 普普通通的表单页面:

 html代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>表单页面</title>
  <!-- 引入样式 --> 
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/element-ui/lib/theme-chalk/index.css" rel="external nofollow" >
  <!-- 引入组件库 -->
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/element-ui/lib/index.js"></script>  
</head>
<style>
    #app {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 20px;
    margin-top: 10vh;
    }
    html{
    width: 100%;
    height: 100%;
    background: #f0faff;
    }
    .el-form {
    max-width: 600px;
    width: 100%;
    box-shadow: 1px 1px 8px #dedede;
    padding: 30px;
    border-radius: 10px;
    background: #fff;
    }
    .el-row {
    margin-bottom: 20px;
    }
    /* .el-button {
    width: 100%;
    } */
</style>
<body>
  <div id="app">
    <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
      <el-row>
        <h3>业务数据导入终端:</h3>
      </el-row>
      <el-row>
        <el-form-item label="邮箱" prop="email">
        <el-input placeholder="请输入接收通知的邮箱" v-model="formData.email"></el-input>
        </el-form-item>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="IP地址" prop="ip">
            <el-input v-model="formData.ip"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="端口" prop="port">
            <el-input v-model="formData.port"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="账号" prop="username">
            <el-input v-model="formData.username"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input v-model="formData.password" type="password"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="数据库" prop="database">
            <el-input v-model="formData.database"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="表名" prop="table">
            <el-input v-model="formData.table"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="上传文件">
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="uploadUrl"
              :before-upload="beforeUpload"
              accept=".xlsx,.xls"
              :limit="1"
              :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="text-align: center; margin-top: 20px;">
          <el-button type="primary" @click="submitForm" :disabled="disabled">{{buttonText }}</el-button>
          <el-button type="danger" @click="clear">清除缓存</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
  <script>
    new Vue({
      el: '#app',
      data() {
        return {
          timer:0,
          limitTime: 1 * 60, // 限制时间为10分钟
          disabled:false,
          formRules:{
                email:[
                  { required: true, message: '请输入联系邮箱', trigger: 'blur' }
                ],
                ip: [
                    { required: true, message: '请输入ip', trigger: 'blur' }
                ],
                port: [
                    { required: true, message: '请输入端口', trigger: 'blur' }
                ],
                username: [
                    { required: true, message: '请输入账号', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ],
                database: [
                    { required: true, message: '请输入数据库', trigger: 'blur' }
                ],
                table: [
                    { required: true, message: '请输入表名', trigger: 'blur' }
                ],
          },
          formData: {
            email:'',
            ip: '',
            port: '',
            username: '',
            password: '',
            database: '',
            table: '',
          },
          uploadUrl: '/upload'  // 文件上传的接口地址
        };
      },
      mounted(){
        var obj = localStorage.getItem("formData")||"";
        var timer = localStorage.getItem("disabled")||"";
        if(timer){  //定时还没结束,重置
          this.disabled = true;
          this.timer = this.limitTime;
          const countdown = setInterval(() => {
              this.timer--;
              if (this.timer <= 0) {
                localStorage.removeItem("disabled");
                clearInterval(countdown);
                this.disabled = false;
              }
          }, 1000);
        }
        if(obj){
          this.formData = JSON.parse(obj);
        }
      },
      computed: {
        buttonText() {
          if (this.disabled) {
            const minutes = Math.floor(this.timer / 60);
            const seconds = this.timer % 60;
            return `禁用中 (${minutes}:${String(seconds).padStart(2, '0')})`;
          } else {
            return '提交';
          }
        },
      },
      methods: {
        beforeUpload(file) {
          // 上传文件之前的钩子函数,可用于校验文件类型等
          const isExcel = ((file.type === 'application/vnd.ms-excel')||(file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'));
          return isExcel;
        },
        clear(){
          this.$confirm('该操作会清除本地保存的数据信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          localStorage.clear();
          this.$message({
            type: 'success',
            message: '清除成功'
          });
          setTimeout(()=>{window.location.reload();},1000)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        },
        submitForm() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    // 提交表单的函数,将表单数据和文件一起发送给后端
                    const formData = new FormData();
                    formData.append('email', this.formData.email);
                    formData.append('ip', this.formData.ip);
                    formData.append('port', this.formData.port);
                    formData.append('access', this.formData.username);
                    formData.append('password', this.formData.password);
                    formData.append('dataName', this.formData.database);
                    formData.append('tableName', this.formData.table);
                    console.log(this.$refs.upload.uploadFiles[0]);
                    if(this.$refs.upload.uploadFiles[0]&&this.beforeUpload(this.$refs.upload.uploadFiles[0].raw)){
                        const file = this.$refs.upload.uploadFiles[0].raw;
                        formData.append('file', file);
                    }else{
                        this.$message.error('请上传excel文件');
                        return;
                    }
                     localStorage.setItem("formData",JSON.stringify(this.formData));
                     this.disabled = true;
                     localStorage.setItem("disabled",this.disabled)
                     this.timer = this.limitTime;
                     const countdown = setInterval(() => {
                      this.timer--;
                      if (this.timer <= 0) {
                        localStorage.removeItem("disabled");
                        clearInterval(countdown);
                        this.disabled = false;
                      }
                    }, 1000);
                    // 发送表单数据和文件给后端
                    fetch('http://localhost/from/uploadExcel', {
                        method: 'POST',
                        body: formData
                    })
                        .then(response => response.json())
                        .then(data => {
                        console.log('提交成功', data);
                          if(data.code==200){
                            this.$message({
                              message: data.msg,
                              type: 'success'
                            });
                          }else{
                            this.$message({
                              message: data.msg,
                              type: 'warning'
                            });
                          }
                        // 处理后端返回的数据
                        })
                        .catch(error => {
                        console.error('提交失败', error);
                        // 处理提交失败的情况
                        });
                } else {
                this.$message.error('请将表单补充完整');
                }
            });
        }
      }
    });
  </script>
</body>
</html>

到此这篇关于vue.js+element-ui的基础表单的文章就介绍到这了,更多相关vue.js element-ui表单内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文