• mockjs的案例


    mockjs实现数据的增删改查

    mock/index.js

    import Mock from "mockjs";
    
    //随机生成数据
    let { newsList } = Mock.mock({
      "newsList|40-60": [
        {
          id: "@increment()",
          title: "@ctitle()",
          content: "@cparagraph(5)",
          img_url: "@image('100x100','#fff','dd524d','png','x')",
          add_time: "@date(yyyy-MM-dd)",
        },
      ],
    });
    
    //获取get中url的query参数值
    function getQuery(url, name) {
      const index = url.indexOf("?");
      //如果有参数,就是有?
      if (index !== -1) {
        const queryArray = url.slice(index + 1).split("&");
        //再截取参数的键值对
        for (let i = 0; i < queryArray.length; i++) {
          if (queryArray[i].split("=")[0] === name)
            //返回指定query参数的值
            return queryArray[i].split("=")[1];
        }
      }
      return null;
    }
    
    //定义新闻列表获取列表,get请求url会有query参数,所以url使用正则来匹配
    Mock.mock(/\/api\/news/, "get", (option) => {
      //option获取url地址
      //   console.log(option.url);
      //页码,起始为1
      const pageIndex = getQuery(option.url, "pageIndex");
      //每页数量
      const pageSize = getQuery(option.url, "pageSize");
    
      /**
       * 分页,pageIndex和pageSize的逻辑
       * 第1页,0-9号数据
       * 第2页,10-19号数据
       * .......
       */
    
      //每页的起始数据号,偏移量
      const start = (pageIndex - 1) * pageSize;
      //截止数据号
      const end = pageIndex * pageSize;
      //数据的截取,slice不包含最后索引的值
      const list = newsList.slice(start, end);
    
      return {
        status: 200,
        message: "获取新闻列表成功",
        list: list,
        total: newsList.length,
      };
    });
    
    //添加新闻
    Mock.mock("/api/post/news", "post", (option) => {
      //option中的body接收传递的参数数据
      const body = JSON.parse(option.body);
      //添加的新的mock数据
      const { news } = Mock.mock({
        news: {
          id: "@increment()",
          title: body.title,
          content: body.content,
          img_url: "@image('100x100','#fff','dd524d','png','x')",
          add_time: "@date(yyyy-MM-dd)",
        },
      });
      newsList.unshift(news);
      return {
        status: 200,
        message: "添加新闻成功",
        list: newsList,
        total: newsList.length,
      };
    });
    //编辑新闻
    Mock.mock("/api/edit/news", "put", (option) => {
      const body = JSON.parse(option.body);
      console.log(body);
      newsList = newsList.map((item) => {
        if (item.id === body.id) item = body;
        return item;
      });
      console.log(newsList);
      return {
        status: 200,
        message: "编辑新闻成功",
      };
    });
    //删除新闻
    Mock.mock("/api/delete/news", "delete", (option) => {
      const newsId = JSON.parse(option.body).id;
      console.log(newsId);
      //   newsList = newsList.filter((item) => item.id !== newsId);
      const indexDelete = newsList.findIndex((item) => item.id === newsId);
      newsList.splice(indexDelete, 1);
      return {
        status: 200,
        message: "删除新闻成功",
      };
    });
    //根据id查询指定新闻
    Mock.mock(/\/api\/getNews/, "get", (option) => {
      console.log(option.url);
      const urlArr = option.url.split("/");
      //获取url中的id
      const newsId = parseInt(urlArr[urlArr.length - 1]);
      const news = newsList.find((item) => item.id === newsId);
      console.log(news);
      return {
        status: 200,
        message: "获取指定新闻成功",
        news,
      };
    });
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125

    app.vue

    <template>
      <div>
        
        <div class="add">
          <input type="text" v-model="title" placeholder="输入标题" />
          <input type="text" v-model="content" placeholder="输入内容" />
          <button @click="add">添加button>
        div>
        
        <div class="news_list">
          <table>
            <tr>
              <th>图片th>
              <th>标题th>
              <th>内容th>
              <th>时间th>
              <th>操作th>
            tr>
            <tr v-for="item in list" :key="item.id">
              <td><img :src="item.img_url" alt="" />td>
              <td>{{ item.title }}td>
              <td>{{ item.content }}td>
              <td>{{ item.add_time }}td>
              <td>
                <button class="edit" @click="edit(item.id)">编辑button
                ><button class="remove" @click="remove(item.id)">删除button>
              td>
            tr>
          table>
        div>
    
        
        <div class="pages">
          <button @click="prevPage">上一页button>
          <button @click="nextPage">下一页button>
        div>
        <el-dialog
          :show-close="false"
          title="编辑新闻"
          :visible="dialogVisible"
          width="30%"
        >
          <el-form ref="form" :rules="rules" :model="form" label-width="80px">
            <el-form-item label="新闻标题" prop="title">
              <el-input v-model="form.title">el-input>
            el-form-item>
            <el-form-item label="新闻内容" prop="content">
              <el-input v-model="form.content">el-input>
            el-form-item>
          el-form>
    
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消el-button>
            <el-button type="primary" @click="submitForm">确 定el-button>
          span>
        el-dialog>
      div>
    template>
    
    <script>
    import axios from "axios";
    export default {
      name: "App",
      data() {
        return {
          title: "",
          content: "",
          list: [],
          pageIndex: 1,
          pageSize: 10,
          dialogVisible: false,
          form: {},
          rules: {
            title: [{ required: true, message: "请输入新闻标题", trigger: "blur" }],
            content: [
              { required: true, message: "请输入新闻内容", trigger: "blur" },
            ],
          },
        };
      },
      created() {
        this.getNewsList();
      },
      methods: {
        //获得新闻列表
        getNewsList() {
          axios({
            url: "/api/news",
            method: "get",
            params: {
              pageIndex: this.pageIndex,
              pageSize: this.pageSize,
            },
          }).then(({ data }) => {
            if (data.list.length === 0) return;
            this.list = [];
            this.list = data.list;
          });
        },
        //添加新闻
        add() {
          axios({
            url: "/api/post/news",
            method: "post",
            data: {
              title: this.title,
              content: this.content,
            },
          }).then(({ data }) => {
            this.list = data.list;
            this.pageIndex = 1;
            this.title = "";
            this.content = "";
            this.getNewsList();
          });
        },
        edit(itemId) {
          this.dialogVisible = true;
          axios({
            url: "/api/getNews/" + itemId,
            method: "get",
          }).then(({ data }) => {
            if (data.status === 200) this.form = data.news;
          });
        },
        async submitForm() {
          try {
            await this.$refs.form.validate();
            axios({
              url: "/api/edit/news",
              method: "put",
              data: this.form,
            }).then(({ data }) => {
              if (data.status === 200) {
                this.getNewsList();
                this.dialogVisible = false;
              }
            });
          } catch (err) {
            console.log(err);
          }
        },
        remove(id) {
          axios({
            url: "/api/delete/news",
            method: "delete",
            data: {
              id: id,
            },
          }).then(({ data }) => {
            if (data.status === 200) this.getNewsList();
          });
          if (this.list.length === 1) this.list = [];
        },
        prevPage() {
          this.pageIndex--;
          this.getNewsList();
        },
        nextPage() {
          this.pageIndex++;
          this.getNewsList();
        },
      },
    };
    script>
    
    <style>
    .add input {
      border-radius: 5px;
      border: none;
      outline: none;
      border: 1px solid #999;
      padding: 5px;
      margin-right: 5px;
    }
    button {
      width: 100px;
      height: 30px;
      background: #409eff;
      color: none;
      outline: none;
      border-radius: 5px;
      margin-left: 5px;
      cursor: pointer;
      border: 0;
      color: #fff;
    }
    .news_list {
      width: 1220px;
      height: 495px;
      overflow-y: scroll;
      overflow-x: hidden;
      margin: 10px;
    }
    table {
      border-collapse: collapse;
      height: 495px;
      overflow-y: scroll;
      overflow-x: hidden;
      margin: 10px;
      border: 1px solid rgb(94, 92, 92);
    }
    table th {
      font-size: 16px;
      height: 30px;
      width: 224px;
      font-weight: normal;
      border: 1px solid rgb(94, 92, 92);
    }
    table td {
      font-size: 12px;
      padding: 5px;
      border: 1px solid rgb(94, 92, 92);
    }
    table td:nth-child(4) {
      width: 150px;
    }
    table td:nth-child(2) {
      min-width: 100px;
    }
    table img {
      width: 80px;
      height: 80px;
    }
    table .edit {
      background: green;
    }
    table .remove {
      background: #f56c6c;
    }
    :deep(button.el-button) {
      padding: none;
    }
    style>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
  • 相关阅读:
    黑客(网络安全)技术自学——高效学习
    从零开始的stable diffusion
    Webpack 性能优化 二次编译速度提升3倍!
    Java客户端Http请求工具Okhttp和RestTemplate的详细介绍
    学习gin-vue-admin之创建api和swagger
    三、安全工程练习题(CISSP)
    MongoDB学习路线
    数据结构与算法系列二之链表、哈希表及栈
    Unity 编辑器资源导入处理函数 OnPostprocessTexture :深入解析与实用案例
    select条目对象
  • 原文地址:https://blog.csdn.net/dpl12/article/details/126128500