ElementUI+MockJS基础

1 ElementUI

Element,一套为开发者、设计师和产品经理准备的基于 Vue 2.0 的桌面端组件库。

2 MockJS

Mock.js (官网http://mockjs.com/)是一款模拟数据生成器,旨在帮助前端攻城师独于后端进行开发,帮助编写单元测试。提供了以下模拟功能:
根据数据模板生成模拟数据、模拟 Ajax 请求,生成并返回模拟数据、基于 HTML 模板生成模拟数据。

3 demo

ElementUI+MockJS基础_第1张图片

3.1 安装插件

安装elementui :npm i element-ui -S
main.js:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
/*引入elementui相关的样式和js*/
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.config.productionTip = false
/*使用elementui*/
Vue.use(ElementUI);


/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: ''
})

安装Mock.js :npm install mockjs

3. 2 table表格

User.vue

<template>

  <div>
    <!--
      :data  根据数据展示列表
      @selection-change: 获取选中列表触发事件(返回的是选中的对象列表)
       v-loading="loading" 值为true代表是加载效果
    -->
    <el-table
      :data="tableData"
      v-loading="loading"
      style="width: 100%"
      @selection-change="selectionChange"
    >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        prop="name"
        label="姓名"
      >
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱"
      >
      </el-table-column>
      <el-table-column
        prop="phone"
        label="电话号码">
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建日期">
      </el-table-column>
      
    </el-table>
    

  </div>
</template>

<script>
export default {
    name: 'User',
    data() {
      return “啦啦啦啦”
      }
  }
</script>

<style scoped>

</style>

index.js

import Vue from 'vue'
import Router from 'vue-router'
import User from '@/components/User'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/user',
      name: 'User',
      component: User
    }
  ]
})

3.3 安装axios---->引入axios模块

安装axios:npm install axios --save

  • main.js
/*引入axios模块*/
import axios from 'axios'
/*对Vue对象进行扩展属性$http*/
Vue.prototype.$http = axios;

3.4 直接发送ajax请求去拿数据—》报404—》因为你要引入user.js文件

  • user.js
//引入mockjs
var Mock = require('mockjs')
let result = Mock.mock({
  'list|203':[{
    'id': '@increment',
    'name': '@cname',
    'phone': /^1[0-9]{10}$/,
    'email': '@email',
    'address': '@county(true)',
    'createTime': '@date("yyyy-MM-dd")'
  }]
})
//console.debug(JSON.stringify(result));

/**
 * 对外暴露的资源
 */
Mock.mock("/user/list","post", function (options) {

  let data = result.list;
  //响应数据
  return {
    data: data
  };
});
  • User.vue
<script>
  import User from "../js/user";
  export default {
    name: 'User',
    data() {
      return {
        loading: true,
        tableData: [],
        selectRows: []
      };
    },
    methods: {
      //加载列表
      loadUserList() {
        this.loading = true;
        this.$http.post("/user/list").then(res => {
          this.tableData = res.data.data;
          this.loading = false;
        });
      },
      //多选
      selectionChange(v) {
        this.selectRows = v;
      }
</script>

<style scoped>

</style>

3.5 分页

3.5.1 把分页条拷贝过来

  • User.vue
<div>
....
 <!--分页-->
    <el-pagination style="margin-top: 10px;"
                   @size-change="sizeChange"
                   @current-change="currentChange"
                   :current-page="currentPage"
                   :page-sizes="pageSizes"
                   :page-size="pageSize"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="total">
    </el-pagination>
    </div>

3.5.2 给一些数据写上默认值

  • User.vue
data() {
      return {
        loading: true,
        tableData: [],
        selectRows: [],

        //分页相关
        //当前页
        currentPage: 1,
        //每页条数集合
        pageSizes: [5, 10, 15, 20],
        //每页条数
        pageSize: 10,
        //总数
        total: 0,
      };
    }
methods:{...
//每页条数改变
      sizeChange(v) {
        this.currentPage = 1;
        this.pageSize = v;
        this.loadUserList();
        //加载框
        this.loading = true;
      },
      //当前页改变
      currentChange(v) {
        this.currentPage = v;
        this.loadUserList();
        //加载框
        this.loading = true
      }
      }

3.6 获取列表传递参数(当前页,每页条数)—》后台会自动计算,返回列表数据和总条数

  • user.js
Mock.mock("/user/list","post", function (options) {
  //获取json字符串
  let paramJsonStr = options.body;
  //将字符串转换为json格式
  let paramjson = JSON.parse(paramJsonStr);

  //获取当前页
  let currentPage = paramjson.currentPage;
  //获取每页条数
  let pageSize = paramjson.pageSize;

  let data = result.list;
  let begin = (currentPage - 1) * pageSize;
  let end = currentPage*pageSize;
  //响应数据
  return {
    data: data.slice(begin,end),
    total:result.list.length
  };
});


3.7 前端获取列表,前端获取总条数(恭喜大家分页完成)

  • User.vue
methods: {
      //加载列表
      loadUserList() {
        //查询传递参数
        let params = {
          "currentPage": this.currentPage,
          "pageSize": this.pageSize
        }
        this.loading = true;
        this.$http.post("/user/list", params).then(res => {
          this.tableData = res.data.data;
          this.total = res.data.total;
          this.loading = false;
        });
      }
  }

3.8 把操作对应的2个按钮拷贝过来(编辑/删除)

  • User.vue
 <el-table>
 ....
<!--操作-->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

3.9 删除(当前行对应的索引, 当前行对应的对象)

User.js

Mock.mock("/user/remove","post", function (options) {
  //获取json字符串
  let paramJsonStr = options.body;
  //将字符串转换为json格式
  let paramjson = JSON.parse(paramJsonStr);
  console.log(paramjson)
  let msg = "";
  if (paramjson.name){
    msg = paramjson.name + "    删除成功!"
  }else {
    msg = "共删除" + paramjson.rows.length + "条数据"
  }
  //响应数据
  return {
    success:true,
    msg: msg
  };
});

3.10 确认删除

User.vue

 //删除一条数据
      handleDelete(i, r) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.post("/user/remove", r).then(res => {
            if (res.data.success) {
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              this.loadUserList();
            }
          })
        }).catch(() => {

        });
      }

3.11批量删除

User.vue

//template
 <!--批量删除-->
    <el-button type="danger" style="float: left;margin-left: 20px" @click="batchRemove">删除</el-button>
   //js
//批量删除
      batchRemove() {
        if (!this.selectRows.length) {
          this.$message.error('亲!请选中数据进行删除哦!!');
          return;
        }
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.post("/user/remove", {"rows": this.selectRows}).then(res => {
            if (res.data.success) {
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              this.loadUserList();
            }
          })
        }).catch(() => {

        });
      },

3.12 高级查询(双向绑定)

User.vue

 <!--查询的form表单-->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="用户名">
        <el-input v-model="searchForm.name" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="searchForm.email" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchSubmit">查询</el-button>
      </el-form-item>
    </el-form>

data:{
return {
//搜索条件form model
        searchForm:{
          name:"",
          email:""
        }
    }
 }

methods:{
 //搜索框
      searchSubmit(){
        this.$message({
          type: 'success',
          message: this.searchForm.name+ " " +this.searchForm.email
        });
        this.loadUserList();
      }
}

3.13 新增添加按钮

<!--添加-->
    <el-button type="primary" style="float: left;" @click="add">新增</el-button>

3.13.1修改标题

 //新增
      add(){
        for(let k in this.form){
          this.form[k] = ""
        }
        this.visible = true,
        this.title = "添加用户"
      }

3.13.2弹出窗体

<!--修改、添加弹出框-->
    <el-dialog :visible.sync="visible" :title="title">
      <el-form :model="form" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="visible = false">确 定</el-button>
        </span>
    </el-dialog>

3.14编辑

  handleEdit(i, r) {
        for(let k in r){
          this.form[k] = r[k]
        }
        this.visible = true,
          this.title = "更新用户"
      }

你可能感兴趣的:(vue,前端,eelementUI)