vue2.0+axios+elementUI完成增编削查

近来尝试运用vue+element完成增编削查功用,在完成的过程当中遇到了蛮多题目,如今总结以下:
起首装置相干的插件
1、依据vue官网引荐,运用axios举行前背景交互,装置axios
npm install axios -S
2、装置elementUI,官网
npm i element-ui -S
3、装置 loader 模块
npm install style-loader -D
npm install css-loader -D

接下来举行相干设置
1、在build目录下的webpack.base.conf.js文件中增添以下代码
{

test: /\.sass$/,
loaders: ['style', 'css', 'sass']

}
2、在main.js中引入
import ElementUI from ‘element-ui‘
import ‘element-ui/lib/theme-default/index.css‘
Vue.use(ElementUI)

接下来完成增编削查功用
贴出table.vue(现在完成了增、删两个功用)

<template>
  <section>
    <el-col :span="24" class="toolbar" style="padding-bottom: 0; text-align: left">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.author" placeholder="作者"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getUsers">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--为了完成分页bookData.slice((currentPage-1)*pageSize,currentPage*pageSize)-->
    <el-col :span="24" style="background: #ff0">
      <el-table border
        :data="bookData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
        :loading="listLoading"
        @selection-change="selectionRowsChange"
        style="width: 100%; text-align: left;">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="#" width="60"></el-table-column>
        <el-table-column prop="author" label="作者" width="200"></el-table-column>
        <el-table-column prop="title" label="书名" width="200"></el-table-column>
        <el-table-column prop="price" label="单价" width="120"></el-table-column>
        <el-table-column prop="publish" label="出书社" width="200"></el-table-column>
        <el-table-column prop="publishDate" label="出书日期"></el-table-column>
        <el-table-column label="操纵" width="250">
          <template slot-scope="scope">
            <!--由elementui供应,scope.$index和scope.row是为了轻易与背景举行数据交互,背面的删除函数中会用到-->
            <el-button size="mini">编辑</el-button>
            <el-button size="mini" type="danger"
              @click="removeUser(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>

    <el-col :span="24" style="margin-top: 20px; text-align: left">
      <el-button type="danger" @click="batchesRemove">
        批量删除
      </el-button>
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :total= "total"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page.sync="currentPage"
        style="float: right;"></el-pagination>
    </el-col>

    <!--增添书本内容-->
    <el-dialog
      title="新增书本"
      :visible.sync="dialogCreateVisible"
      style="text-align: left">
      <el-form :rules="addFormRules" ref="addForm" :model="addForm" :label-width="addFormLabelWidth">
        <el-form-item label="作者" prop="author">
          <el-input v-model="addForm.author" name="author" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="书名" prop="title">
          <el-input v-model="addForm.title" name="title" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="addForm.price" name="price" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="出书社" prop="publish">
          <el-input v-model="addForm.publish" name="publish" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="出书日期" prop="publishDate">
          <!--<el-input v-model="addForm.publishDate"></el-input>-->
          <el-date-picker v-model="addForm.publishDate" name="publishDate" type="date" placeholder="挑选日期"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createReset">作废</el-button>
        <el-button @click.native="createSubmit" :loading="addLoading" type="primary">肯定</el-button>
      </div>
    </el-dialog>

    <!--编辑书本信息-->
    <el-dialog
      title="修正书本信息"
      :visible.sync="dialogUpdateVisible"
      :close-on-click-modal="false"  style="text-align: left">
      <el-form :model="updateForm" :rules="updateRules" ref="update" label-width="100px">
        <el-form-item label="作者" prop="authorName">
          <el-input v-model="updateForm.authorName"></el-input>
        </el-form-item>
        <el-form-item label="书名" prop="title">
          <el-input v-model="updateForm.title"></el-input>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="updateForm.price"></el-input>
        </el-form-item>
        <el-form-item label="出书社" prop="publish">
          <el-input v-model="updateForm.publish"></el-input>
        </el-form-item>
        <el-form-item label="出书日期" prop="publishDate">
          <!--<el-input v-model="updateForm.publishDate"></el-input>-->
          <el-date-picker type="date" placeholder="挑选日期" v-model="updateForm.publishDate"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editReset">作废</el-button>
        <el-button type="primary" :loading="updateLoading" @click.native="editSubmit">肯定</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>

  export default {
    name: "add",
    data() {
      return {
        bookData: [],
        filters: {
          author: '',
        },
        total: 0,
        pageSize: 0,
        currentPage: 1,
        listLoading: false,
        sels: [],  // 选中的列

        // 新增表单
        addForm: {
          author: '',
          title: '',
          price: '',
          publish: '',
          publishDate: ''
        },
        addFormRules: {
          author: [
            { required: true, message: '请输入作者', trigger: 'blur'}
          ],
          title: [
            { required: true, message: '请输入书名', trigger: 'blur'}
          ],
          price: [
            { required: true, message: '请输入书本单价 ', trigger: 'blur' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '单价必需为数字,而且小数点后不凌驾两位', trigger: 'blur' }
          ],
          publish: [
            { required: true, message: '请输入出书社名', trigger: 'blur' }
          ]
        },
        dialogCreateVisible: false,
        addFormLabelWidth: '80px',
        addLoading: false,

        // 编辑表单
        updateForm: {
          authorName: '',
          title: '',
          price: '',
          publish: '',
          publishDate: ''
        },
        updateRules: {
          authorName: [{
            message: '请输入姓名',
            trigger: 'blur',
          }, {
            min: 3,
            max: 15,
            message: '长度在3-15个字符'
          }],
          title: [{
            message: '请输入书名'
          }],
          price: [{
            type: 'number',
            // pattern: '',
            message: '请输入最多两位小数的单价'
          }]
        },
        updateLoading: false,
        dialogUpdateVisible: false  // 编辑对话框的显现状况
      }
    },
    methods: {
      // 转变页码
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getUsers();
      },
      // 转变每页显现的数目
      handleSizeChange(val) {
        this.pageSize = val;
      },
      //  查询, 猎取用户列表
      getUsers() { 
      
      // 运用URLSearchParams函数的缘由:在与背景举行交互时,假如背景运用的字符编码花样与axios的编码花样不一致,会致使后端不能吸收到前端传过去的参数,为了处理这一题目,
        let para = new URLSearchParams();
        para.append("author", this.filters.author);
        this.listLoading = true;
        this.$ajax({
          methods: 'post',
          url: 'http://xxx.xx.xxx.xxx:8099/InfoManage/bookList',
          data: para,
        }).then(res => {
        
          this.total = res.data.length;
          this.pageSize = 20;  // 每页展现的条目数
          this.author = res.data[0].author;  // 将背景传过来的数据填充到前端表单页面中
          this.bookData = res.data;
          this.listLoading = false;
       
        }).catch( err => {
          console.log(err);
        })
      },

    //  显现新增
      handleAdd () {
        this.dialogCreateVisible = true;
        this.addForm = {
          author: '',
          title: '',
          price: '',
          publish: '',
          publishDate: ''
        };
      },
      //  提交新增书本信息
      createSubmit() {
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交?', '提醒', {}).then(() => {
              this.addLoading = true;
           
              let addPara = new URLSearchParams();
              addPara.append("id", this.addForm.id);
              addPara.append("title", this.addForm.title);
              addPara.append("author", this.addForm.author);
              addPara.append("price", this.addForm.price);
              addPara.append("publish", this.addForm.publish);
              addPara.append("publishDate", this.addForm.publishDate);

              this.$ajax({
                method: 'post',
                url: 'http://xxx.xx.xxx.xxx:8099/InfoManage/addBook',
                data:addPara,
              }).then(res => {
                console.log(eval("("+res.data+")"));
                console.log(addPara);
                console.log(addPara.author);
                console.log(res.data);
                this.addLoading = false;
                this.$message({
                  type: 'success',
                  message: '提交胜利!'
                });
                this.dialogCreateVisible = false;
                this.getUsers();
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已作废新增'
              });
            })
          }
          else {
            console.log('error');
            return false;
          }
        })
      },
      //  显现编辑页面
      handleEdit(index, row) {
        console.log('click success');
        this.dialogUpdateVisible = true;
        // this.updateForm = Object.assign({}, row)
        let updateParas = new URLSearchParams();
        updateParas.append("id", row.id);
        this.$ajax({
          method: 'post',
          url: 'http://xxx.xx.xxx.xxx:8099/InfoManage/loadBook',
          data: updateParas
        }).then(res => {
          this.updateForm = res.data;
        })
      },
      //  编辑页面重置
      createReset() {
        this.dialogCreateVisible = false;
        this.$refs.addForm.resetFields();
      },
      
      //  提交编辑后书本信息
      editSubmit() {
        this.$refs.update.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交?', '提醒', {}).then(() => {
              this.addLoading = true;
              let editParas = new URLSearchParams();
              editParas.append("id", this.updateForm.id);
              editParas.append("author", this.updateForm.author);
              editParas.append("title", this.updateForm.title);
              editParas.append("price", this.updateForm.price);
              editParas.append("publish", this.updateForm.publish);
              editParas.append("publishDate", this.updateForm.publishDate);

              this.$ajax({
                method: 'post',
                url: 'http://xxx.xx.xxx.xxx:8099/InfoManage/updateBook',
                data: editParas
              }).then(res => {
                console.log(res.data);
                // this.bookData = res.data;
                this.updateLoading = false;
                this.$message({
                  type: 'success',
                  message: '提交胜利!'
                });
                this.dialogUpdateVisible = false;
                this.getUsers();
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已作废编辑'
              });
            })
          }
        })
      },
      // 单个删除书本信息
      removeUser(index, row) {
        this.$confirm('肯定删除该纪录吗? ', '提醒', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          let delParas = new URLSearchParams();
           delParas.append("id", row.id ); // 相应template中scope.row,完成向背景传送当前row的id

        //  向服务端要求删除
          this.$ajax({
            method: 'post',
            url: 'http://xxx.xx.xxx.xxx:8099/InfoManage/delectBook',
            data:delParas,
          }).then(res => {
            this.listLoading = false;
            this.$message({
              message: '删除胜利',
              type: 'success'
            });
            this.getUsers();
          });
        }).catch(() => {
          console.log('删除失利');
        })
      },
        // 挑选选中的行
      selectionRowsChange(sels) {
        // 将选中的行放进sels数组
        this.sels = sels;
      },
      //  批量删除书本
      batchesRemove() {
        // 将数组转化string范例 
        var idArray = this.sels.map(item => item.id).toString();
        this.$confirm('确认删除选中纪录吗?', '提醒', {
          type: 'warning',
        }).then(() => {
          let batchPara = new URLSearchParams();
          batchPara.append("idArray", idArray);
          this.$ajax({
            method: 'post',
            url: 'http://xxx.xx.xxx.xxx:8099/InfoManage/batchDeleting',
            data: batchPara
          }).then((res) => {
            this.$message({
              message: '删除胜利',
              type: 'success'
            });
            this.getUsers();
          })
        }).catch(() => {})

      },
    },
    // mounted的作用就是保证在进入table.vue文件时就加载用户数据
    mounted() {
      this.getUsers();
    }
  }
</script>

<style scoped type="scss">
  .el-table td {
    text-align: left;
  }
</style>

上面代码中最主要的一点是背景能够吸收不到前端数据,处理方案代码中已给出,详细缘由没有写明,人人想看能够看
https://blog.csdn.net/csdn_yu…
这篇博客写的比较清楚
我采纳的是第一种方法:
在main.js文件中增添
axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’;
然后在挪用接口时运用 URLSearchParams 通报参数,比方猎取用户数据时
let para = new URLSearchParams();
para.append(“author”, this.filters.author); // append中的author、id、idArray都是要和背景供应的参数雷同,不然数据参数将传不过去
this.$ajax({
methods: ‘post’,
url: ‘http://xxx.xx.xxx.xxx:8099/InfoManage/bookList’,
data: para,
}).then(res => {
console.log(res);
}).catch( err => {
console.log(err);
})

实在,完成增编削查最主要的是在找到准确的参数,并将参数通报给背景,功用的完成主如果背景,前端只担任数据展现。
增编削查功用悉数完成。

    原文作者:Nanana
    原文地址: https://segmentfault.com/a/1190000015834632
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞