vue-cli——mockjs增刪改查小案例

mockjs可以幫我們生成隨機(jī)數(shù)據(jù),攔截ajax請(qǐng)求
安裝npm intall mockjs -D(開(kāi)發(fā)依賴,不參與打包。默認(rèn)-S)
新建文件src->mock->index.js
在mian.js中引入 impot './mock'

<template>
  <div class="home">
    <div class="fq" v-show="isfq"></div>
    <h2>課程信息</h2>
    <button
      @click="
        isEdit = true;
        isfq = true;
      "
      class="addsub btn btn-info"
    >
      添加課程
    </button>
    <table class="table table-striped table-bordered table-condensed">
      <thead>
        <tr>
          <th>課程編號(hào)</th>
          <th>課程名稱</th>
          <th>課時(shí)</th>
          <th>年級(jí)</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="s in subs" :key="s.SubjectId">
          <td>{{ s.SubjectId }}</td>
          <td>{{ s.SubjectName }}</td>
          <td>{{ s.ClassHour }}</td>
          <td>{{ s.Grade.GradeName }}</td>
          <td>
            <button class="btn btn-warning" @click="getOne(s.SubjectId)">
              修改</button
            >&nbsp;
            <button class="btn btn-danger" @click="delSubject(s.SubjectId)">
              刪除
            </button>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="edit" v-show="isEdit">
      <span class="x" @click="clear">X</span>
      <p>
        <span>課程名稱:</span><input type="text" v-model="sub.subjectName" />
      </p>
      <p>
        <span>課時(shí):</span><input type="text" v-model.number="sub.classHour" />
      </p>
      <p>
        <span>年級(jí):</span
        ><select v-model="sub.gradeId">
          <option v-for="i in Grade" :key="i.GradeId" :value="i.GradeId">
            {{ i.GradeName }}
          </option>
        </select>
      </p>
      <p>
        <button @click="addSubject" v-show="isadd">添加</button>&nbsp;
        <button @click="updateSubject" v-show="!isadd">修改</button>&nbsp;

        <button>取消</button>
      </p>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import axios from "axios";
export default {
  name: "Home",
  data() {
    return {
      isfq: false,
      isEdit: false,
      isadd: true,
      subs: [],
      sub: {
        subjectName: "",
        classHour: 0,
        gradeId: 1,
      },
      Grade: [],
    };
  },
  created() {
    this.loadSubjects();
    this.loadGrades();
  },
  methods: {
    async loadSubjects() {
      let { data } = await axios.get("http://www.bingjs.com:81/Subject/GetAll");
      this.subs = data;
    },
    async loadGrades() {
      let { data } = await axios.get("http://www.bingjs.com:81/Grade/GetAll");
      this.Grade = data;
    },
    async addSubject() {
      let { data } = await axios.post(
        "http://www.bingjs.com:81/Subject/Add",
        this.sub
      );
      if (data) {
        this.clear();
        alert("添加成功");
        this.loadSubjects();
      }
    },
    async loadSubject(subjectId) {
      let { data: { SubjectName, GradeId, ClassHour },} = await axios.get("http://www.bingjs.com:81/Subject/GetSubjectById", {
        params: {
          subjectId,
        },
      });
      this.sub = {
        subjectId,
        subjectName: SubjectName,
        classHour: ClassHour,
        gradeId: GradeId,
      };
    },
    getOne(id) {
      this.isEdit = true;
      this.isfq = true;
      this.isadd = false;
      this.loadSubject(id);
    },
    clear() {
      this.isEdit = false;
      this.isfq = false;
      this.isadd = true;
      this.sub = {
        subjectName: "",
        classHour: 0,
        gradeId: 1,
      };
    },
    async updateSubject() {
      let {data} = await axios.post('http://www.bingjs.com:81/Subject/Update',this.sub)
      if(data){
        alert('修改成功')
        this.loadSubjects()
        this.clear()
      }

    },
    async delSubject(subjectId) {
      if (!confirm("是否確認(rèn)刪除?")) return;
      let { data } = await axios.post(
        "http://www.bingjs.com:81/Subject/Delete",
        { subjectId }
      );
      if (data) {
        alert("刪除成功");
        this.loadSubjects();
      }
    },
  },
  components: {},
};
</script>
<style lang="scss" scoped>
.home {
  .fq {
    width: 100vw;
    height: 100vh;
    position: fixed;
    background: #eee;
    opacity: 0.5;
  }
  padding: 10px;
  border: 1px solid #eee;
  .addsub {
    margin-bottom: 20px;
    outline: none;
  }
  .table {
    width: 1200px;
    th,
    td {
      text-align: center;
      line-height: 34px;
      button {
        outline: none;
      }
    }
  }
  .edit {
    width: 320px;
    border: 1px solid #666;
    height: 220px;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    background: white;
    padding: 30px 20px;
    box-sizing: border-box;
    .x {
      position: absolute;
      right: 10px;
      top: 10px;
      width: 30px;
      height: 30px;
      line-height: 30px;
      font-size: 20px;
      background: red;
      color: white;
      text-align: center;
      border-radius: 50%;
      cursor: pointer;
      user-select: none;
    }
    p {
      margin: 20px 0;
      span {
        display: inline-block;
        width: 70px;
        text-align: center;
      }
      &:last-of-type {
        text-align: center;
      }
    }
  }
}
</style>

mock頁(yè)面

1、生成隨機(jī)數(shù)據(jù)
Mock.mock方法生成隨機(jī)數(shù)據(jù),里面寫(xiě)對(duì)象里面是數(shù)據(jù),數(shù)據(jù)里面是對(duì)象
一次mock方法可以生成很多數(shù)據(jù),mock方法返回的是對(duì)象,直接結(jié)構(gòu)出設(shè)置的list數(shù)據(jù)
@name返回英文姓名
@cname返回姓名
@datetima返回日期事件
@integer(20-80)返回是數(shù)字
800隨機(jī)生成1-800中的數(shù)組
2、攔截ajax請(qǐng)求
就是發(fā)送請(qǐng)求時(shí)會(huì)被mock攔截,轉(zhuǎn)向這個(gè)假的omck數(shù)據(jù)。
攔下了你要請(qǐng)求的數(shù)據(jù)把mock的數(shù)據(jù)給你
查看是否攔截成功可在控制臺(tái)network->feach/XHR
mock()方法的參數(shù):請(qǐng)求地址,請(qǐng)求方式,回調(diào)函數(shù)
options對(duì)象的屬性包括:
url是完整的請(qǐng)求地址
type是請(qǐng)求類型post、get
body是post請(qǐng)求的請(qǐng)求體
get請(qǐng)求的參數(shù)最終會(huì)拼在url后面,所以隨機(jī)數(shù)據(jù)的地址要寫(xiě)正則

//  mockjs提供了兩個(gè)功能:1.生成隨機(jī)數(shù)據(jù) 2.攔截 Ajax 請(qǐng)求
// 導(dǎo)入mockjs
import Mock from "mockjs";

// 設(shè)置請(qǐng)求延遲時(shí)間
Mock.setup({
  //延遲時(shí)間200毫秒
  timeout: 200,
});

// 生成一個(gè)數(shù)組數(shù)據(jù)
const { subjects,grades } = Mock.mock({
  "grades|3":[
      {
        "GradeId|+1":1,
        "GradeName":"@cname"
      }
  ],
  //隨機(jī)生成一個(gè)10到20條的數(shù)組
  "subjects|5-10": [
    {
      "SubjectId|+1": 1,
      SubjectName: "@ctitle(10,15)",
      ClassHour: "@integer(20,80)",
      GradeId:"@integer(1,3)"
    },
  ],
});
Subjects.forEach(i => {
    i.Grade = {
        GradeId: i.GradeId,
        GradeName: Grades.find(r => r.GradeId === i.GradeId).GradeName
這里是給Subjects每個(gè)對(duì)象添加一個(gè)屬性為Grade的對(duì)象
    }
})
// 攔截添加請(qǐng)求
Mock.mock(/http:\/\/www.bingjs.com:81\/Subject\/GetAll/, "get", () => {
    return Subjects;   這里的return返回的是隨機(jī)生成的數(shù)據(jù)
});
Mock.mock(/http:\/\/www.bingjs.com:81\/Subject\/GetSubjectById/, "get", ({ url }) => {結(jié)構(gòu)出options中的url
get的params中請(qǐng)求的數(shù)據(jù)可以通過(guò)options中的url獲取,進(jìn)行分割得到請(qǐng)求的數(shù)據(jù)
    let id = url.split('?')[1].split('=')[1]
    let obj = Subjects.find(r => r.SubjectId == id)
    return obj;
});
Mock.mock(/http:\/\/www.bingjs.com:81\/Subject\/Delete/, "post", (options) => {
    let { subjectId } = JSON.parse(options.body)
    let index = Subjects.findIndex(r => r.SubjectId === subjectId)
    Subjects.splice(index, 1)
    return true;
});
Mock.mock(/http:\/\/www.bingjs.com:81\/Subject\/Update/, "post", (options) => {
    let { subjectId, subjectName, classHour, gradeId } = JSON.parse(options.body)
    let obj = Subjects.find(r => r.SubjectId == subjectId)
    obj.SubjectName = subjectName
    obj.ClassHour = classHour
    obj.GradeId = gradeId
    obj.Grade = {
        GradeId: gradeId,
        GradeName: Grades.find(r => r.GradeId === gradeId).GradeName
    }

    return true;
});
Mock.mock(/http:\/\/www.bingjs.com:81\/Subject\/Add/, "post", (options) => {
axios直接用對(duì)象post過(guò)來(lái)的數(shù)據(jù)是字符串,必須要用JSON.pase()轉(zhuǎn)為對(duì)象
    let obj = JSON.parse(options.body)    
    let subject = {
        SubjectId: Subjects[Subjects.length - 1].SubjectId + 1,
        SubjectName: obj.subjectName,

        ClassHour: obj.classHour,
        GradeId: obj.gradeId
    }
    subject.Grade = {
        GradeId: obj.gradeId,
        GradeName: Grades.find(r => r.GradeId === obj.gradeId).GradeName
    }
    Subjects.push(subject)

    return true;
});
Mock.mock(/http:\/\/www.bingjs.com:81\/Grade\/GetAll/, "get", () => {
    return Grades;
});
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容