current position:Home>Vue conducts data simulation through mokejs

Vue conducts data simulation through mokejs

2022-01-27 01:25:01 Nanchen_ forty-two

Use mock Analog data

Create basic projects from scaffolding For scaffold details, please refer to The scaffold This installation Teaching

01、 Install... In the project mock

Two installations The order is as follows :

npm install mockjs

vue add axios 

After installation, it can be installed in node_modules Check whether it is installed as mockjs

 

02、 Create a new folder and create a new folder on it index.js

03、 take mock The folder index.js The file in main.js Import

 04、 Yes index.js add to mock grammar

( Used here to test ) Please get the detailed syntax from the official website  Mock.js

//  Use  Mock
var Mock = require('mockjs')
var data = Mock.mock({
    //  attribute  list  The value of is an array , It contains  1  To  10  Elements 
    'list|1-10': [{
        //  attribute  id  It's a self increasing number , The starting value is  1, Every time  1
        'id|+1': 1
    }]
})
//  Output results 
console.log(JSON.stringify(data, null, 4))

  Download after the test elementui plug-in unit , from vue ui Download

  Next you can use element-ui To realize the request of paging data , Add and delete functions

One 、 Delete vue The original style in

stay index.js Add four kinds of data

//  Use  Mock
var Mock = require('mockjs')
var data = Mock.mock({
    //  attribute  list  The value of is an array , It contains  1  To  10  Elements 
    'list|20-60': [{
        //  attribute  id  It's a self increasing number , The starting value is  1, Every time  1
        "id": '@increment()',
        "title": "@ctitle",
        "content": "@cparagraph",
        "add_time": "@date(yyyy-MM-dd hh:mm:ss)"
    }]
})
//  Output results 
console.log(JSON.stringify(data))

To print here, first convert it into string format , And if only data So the effect is as follows :

  It is particularly difficult to view data , So it needs to be typeset . Like the following :

//  Use  Mock
var Mock = require('mockjs')
var data = Mock.mock({
    //  attribute  list  The value of is an array , It contains  1  To  10  Elements 
    'list|20-60': [{
        //  attribute  id  It's a self increasing number , The starting value is  1, Every time  1
        "id": '@increment()',
        "title": "@ctitle",
        "content": "@cparagraph",
        "add_time": "@date(yyyy-MM-dd hh:mm:ss)"
    }]
})
//  Output results 
console.log(JSON.stringify(data,null,4))

The effect is as follows Shown :

console.log(JSON.stringify(data,null,4))
Mock.mock('/api/get/user','get',(options)=>{
    console.log(options);
    return {
        status: 200,
        message: ' Get news list data successfully ',
        test:data.list
    }
})

App.vue 

 mounted(){
    this.getData()
  },
  methods: {
    getData(){
      this.$axios.get('/api/get/user').then(res=>{
        console.log(res);
      })
    }
  },

 

Next, you can set App.vue The style in

You can extract the required style from the official website :element-ui Official website

, And modify it  

stay div #app Add the following code  

    <h3 style="text-align: center"> Data presentation </h3>

    <!--  add to  -->
    <el-row :gutter="24">
      <el-col :span="8">
        <el-input v-model="title" placeholder=" Please enter a title "></el-input
      ></el-col>
      <el-col :span="8"
        ><el-input v-model="content" placeholder=" Please enter the content "></el-input
      ></el-col>
      <el-col :span="8"
        ><el-button type="primary" @click="handelAdd"> add to </el-button></el-col
      >
    </el-row>
  • adopt row and col Components , And pass col Component's  span  Attribute, we can combine the layout freely .
  • Row Components Provide  gutter  Property to specify the interval between each column , The default interval is 0.

  The effect is as follows :

  The next step is to select the table  

 <el-table
    :data="tableData"
    stripe
    style="width: 100%">
    <el-table-column
      prop="date"
      label=" date "
      width="180">
    </el-table-column>
    <el-table-column
      prop="name"
      label=" full name "
      width="180">
    </el-table-column>
    <el-table-column
      prop="address"
      label=" Address ">
    </el-table-column>
  </el-table>
export default {
  name: "app",
  data() {
    return {
      // tableData: [],
      title: "",
      content: "",
      pagenum: 1,
      pagesize: 10,
      total: 0,
      tableData: [
        {
          date: "2016-05-02",
          name: " X.h. ",
          address: " Jinshajiang road, putuo district, Shanghai  1518  get ",
        },
        {
          date: "2016-05-04",
          name: " X.h. ",
          address: " Jinshajiang road, putuo district, Shanghai  1517  get ",
        },
        {
          date: "2016-05-01",
          name: " X.h. ",
          address: " Jinshajiang road, putuo district, Shanghai  1519  get ",
        },
        {
          date: "2016-05-03",
          name: " X.h. ",
          address: " Jinshajiang road, putuo district, Shanghai  1516  get ",
        },
      ],
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    getData() {
      this.$axios.get("/api/get/user").then((res) => {
        console.log(res);
      });
    },
  },
};

  Add delete button

        <el-table-column label=" operation ">
          <template v-slot="scope" >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              > Delete </el-button
            >
          </template>
        </el-table-column>
handleDelete(index, row) {
      console.log(index, row);
    },

Then modify the header name  

The code is as follows :

<template>
  <div id="app">
    <h3 style="text-align: center"> Data presentation </h3>
    <!--  add to  -->
    <el-row :gutter="24">
      <el-col :span="8"><el-input  v-model="title" placeholder=" Please enter a title "></el-input></el-col>
      <el-col :span="8"><el-input  v-model="content" placeholder=" Please enter the content "></el-input></el-col>
      <el-col :span="8">
        <el-button type="primary"> add to </el-button>
      </el-col>
    </el-row>
    <template>
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="date" label=" title " width="180">
        </el-table-column>
        <el-table-column prop="name" label=" Content " width="180">
        </el-table-column>
        <el-table-column prop="address" label=" Time "> </el-table-column>
        <el-table-column label=" operation ">
          <template v-slot="scope">
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              > Delete </el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </template>
  </div>
</template>
<script>
export default {
  name: "app",
  data() {
    return {
      // tableData: [],
      title: "",
      content: "",
      pagenum: 1,
      pagesize: 10,
      total: 0,
      tableData: [
        {
          date: "2016-05-02",
          name: " X.h. ",
          address: " Jinshajiang road, putuo district, Shanghai  1518  get ",
        },
        {
          date: "2016-05-04",
          name: " X.h. ",
          address: " Jinshajiang road, putuo district, Shanghai  1517  get ",
        },
        {
          date: "2016-05-01",
          name: " X.h. ",
          address: " Jinshajiang road, putuo district, Shanghai  1519  get ",
        },
        {
          date: "2016-05-03",
          name: " X.h. ",
          address: " Jinshajiang road, putuo district, Shanghai  1516  get ",
        },
      ],
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    getData() {
      this.$axios.get("/api/get/user").then((res) => {
        console.log(res);
      });
    },
    handleDelete(index, row) {
      console.log(index, row);
    },
  },
};
</script>

<style>
</style>

The effect is as follows :

stay index.js in binding total

Mock.mock('/api/get/user','get',(options)=>{
    console.log(options);
    return {
        status: 200,
        message: ' Get news list data successfully ',
        test:data.list,
        total:data.list.length
    }
})

stay app.vue Delete data items and get data

    getData() {
      this.$axios.get("/api/get/user").then((res) => {
        console.log(res);
        //  Render to page 
        this.tableData = res.data.test
        console.log(this.tableData);
      });
    },

The effect is as follows : 

  Reset width

      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="title" label=" title " width="160">
        </el-table-column>
        <el-table-column prop="content" label=" Content " >
        </el-table-column>
        <el-table-column prop="add_time" label=" Time " width="180"> </el-table-column>
        <el-table-column label=" operation " width="180">
          <template v-slot="scope">
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              > Delete </el-button
            >
          </template>
        </el-table-column>
      </el-table>

The effect is as follows : 

Next, do paging

 <el-pagination style="text-align: center"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage4"
      :page-sizes="[100, 200, 300, 400]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="400">
    </el-pagination>
 methods: {
      handleSizeChange(val) {
        console.log(` each page  ${val}  strip `);
      },
      handleCurrentChange(val) {
        console.log(` The current page : ${val}`);
      }
    },

Because pagination is aligned to the left by default , So add a... To the label style Style to center text

All page rendering has been completed

Next, delete and add effects

 index.js Delete in

First, comment out the paging style , Otherwise, the console will cause errors

 

//  Use regular expressions to write 
Mock.mock(/\/api\/delete\/user/,'post',(options)=>{
    console.log(options);
    return{
        status: 200,
        message: ' Delete successful ',
        list:data.list,
    }
})

app.vue part  

    //  Delete 
    async handleDelete(id) {
      // console.log(index, row);
      //  Pass a parameter id post Just pass it directly 
      //  Deconstruction 
      // const {data,res} = await('/api/get/user',{ id })
      const result = await axios.post('/api/delete/user',{ id })
      console.log(result);
      this.getData()
      //  If it is get request 
/*       const {data,res} = await('/api/get/user',{ 
        params:{
          // id:id
          id
        }
       }) */
    },
/*     handleSizeChange(val) {
      console.log(` each page  ${val}  strip `);
    },
    handleCurrentChange(val) {
      console.log(` The current page : ${val}`);
    }, */

The delete button will be modified :

          <template v-slot="scope">
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row.id)"
              > Delete </el-button
            >
          </template>

  Use async To put axios introduce

 index.js In order to get options Inside body

Mock.mock(/\/api\/delete\/user/,'post',(options)=>{
    console.log(options);
    //  To be converted into the form of an object 
    // const body = options.body
    const body = JSON.parse(options.body)
    console.log(body);
    //  Filtering data 
    return{
        status: 200,
        message: ' Delete successful ',
        list:data.list,
    }
})

  Use findindex Search for complex data types

    const index = data.list.findIndex(item=>item.id === body.id);
    data.list.splice(index,1)

  The effect is as follows :

Of course, you can also add a pop-up window  

  How to add ?

Put the code in app.vue The methods of

this.$confirm(' This operation will permanently delete the file ,  Whether or not to continue ?', ' Tips ', {
          confirmButtonText: ' determine ',
          cancelButtonText: ' Cancel ',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: ' Delete successful !'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: ' Delete cancelled '
          });          
        });

And render the data in the deletion success

this.$confirm(' This operation will permanently delete the file ,  Whether or not to continue ?', ' Tips ', {
          confirmButtonText: ' determine ',
          cancelButtonText: ' Cancel ',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: ' Delete successful !'
          });
        //  hold this.getData Put it here 
          this.getData();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: ' Delete cancelled '
          });          
        });

The effect is as follows :

Add operation  

app.vue

  async handelAdd() {
      if (!this.title || !this.content) {
        alert(' Please be sure to fill in the title and content information !');
        return;
      }
      //  You can use repeated result, Its scope is different 
      const result = await axios.post("/api/add/user", {
        //  The parameters passed in are the title bar and content bar in the label 
        title: this.title,
        content: this.content,
      });
      //  Reload the data 
      console.log(result);
      this.getData();
    //  Empty the contents after entering 
      this.title=''
      this.content=''
    },

  Add a judgment condition ( If it is null , Then a pop-up window will be called to remind the user of incomplete information )

      if (!this.title || !this.content) {
        alert(' Please be sure to fill in the title and content information !');
        return;
      }

 index.js part

Mock.mock(/\/api\/add\/user/,'post',(options)=>{
    console.log(options);
    const body = JSON.parse(options.body)
    data.list.unshift(Mock.mock({
           //  Remember not to add random numbers here  , We should remove the random data and replace it with body.title and body.content
            "id": '@increment()',
            "title": body.title,
            "content": body.content,
            "add_time": "@date(yyyy-MM-dd hh:mm:ss)"
    }))
    return{
        status: 200,
        message: ' Add success ',
        list:data.list,
    }
})

The effect is as follows :

Pagination section

Paging controls

 <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageindex"
      :page-sizes="[1, 3, 5, 7]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

Pagination method :

    handleSizeChange(val) {
      console.log(` each page  ${val}  strip `);
      this.pagesize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      console.log(` The current page : ${val}`);
      this.pageindex = val;
      this.getList();
    },

 index.js part :

I don't want this

Write a new one directly below  

//  A list of data with paging , If there are parameters to be accepted, use regular matching 
// /api/get/news?pageindex=1&pagesize=10
Mock.mock(/\/api\/get\/user/, 'get', (options) => {
  console.log(options)
  //  Get the parameters passed pageindex
  const pageindex = getQuery(options.url,'pageindex')
  //  Get the parameters passed pagesize
  const pagesize = getQuery(options.url,'pagesize')
  //  The starting position of intercepted data 
  const start = (pageindex-1)*pagesize
  //  The end position of intercepted data 
  const end = pageindex*pagesize
  //  Calculate the total number of pages 
  const totalPage = Math.ceil(data.list.length/pagesize)
  //  The starting position of the data :(pageindex-1)*pagesize   End of data :pageindex*pagesize
  const list = pageindex>totalPage?[]:data.list.slice(start,end)

  return {
    status: 200,
    message: ' Get news list successfully ',
    list: list,
    total: data.list.length
  }
})

The parameter name can be taken by itself  

 

  Finally, in the life cycle Just run it first :

  create() {
    this.getData();
  },

The effect is as follows :  

There are minor errors after changing the data in the middle of this chapter , The following code is the complete code

 vue.app part :

<template>
  <div id="app">
    <h3 style="text-align: center"> Data presentation </h3>
    <!--  add to  -->
    <el-row :gutter="24" style="margin: 0">
      <el-col :span="8"
        ><el-input v-model="title" placeholder=" Please enter a title "></el-input
      ></el-col>
      <el-col :span="8"
        ><el-input v-model="content" placeholder=" Please enter the content "></el-input
      ></el-col>
      <el-col :span="8">
        <el-button type="primary" @click="handelAdd"> add to </el-button>
      </el-col>
    </el-row>
    <template>
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="title" label=" title " width="160">
        </el-table-column>
        <el-table-column prop="content" label=" Content "> </el-table-column>
        <el-table-column prop="add_time" label=" Time " width="180">
        </el-table-column>
        <el-table-column label=" operation " width="180">
          <template v-slot="scope">
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row.id)"
              > Delete </el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="text-align: center"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageindex"
        :page-sizes="[1, 3, 5, 7]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </template>
  </div>
</template>
<script>
import axios from "axios";
export default {
  name: "app",
  data() {
    return {
      tableData: [],
      title: "",
      content: "",
      pageindex: 1,
      pagesize: 10,
      total: 0,
    };
  },
  mounted() {
    this.getData();
  },
  create() {
    this.getData();
  },
  methods: {
    getData() {
      //  Write paging 
      this.$axios
        .get("/api/get/user", {
          params: {
            pageindex: this.pageindex,
            pagesize: this.pagesize,
          },
        })
        .then((res) => {
          console.log(res);
          this.tableData = res.data.list;
          // console.log(this.tableData);
          this.total = res.data.total;
        });
    },
    //  Delete 
    async handleDelete(id) {
      this.$confirm(" This operation will permanently delete the file ,  Whether or not to continue ?", " Tips ", {
        confirmButtonText: " determine ",
        cancelButtonText: " Cancel ",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: " Delete successful !",
          });
          this.getData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: " Delete cancelled ",
          });
        });
      // console.log(index, row);
      //  Pass a parameter id post Just pass it directly 
      //  Deconstruction 
      // const {data,res} = await('/api/get/user',{ id })

      const result = await axios.post("/api/delete/user", { id });
      console.log(result);

      //  If it is get request 
      /*       const {data,res} = await('/api/get/user',{ 
        params:{
          // id:id
          id
        } 
       }) */
    },

    //  add to 
    async handelAdd() {
      if (!this.title || !this.content) {
        alert(" Please be sure to fill in the title and content information !");
        return;
      }
      //  You can use repeated result, Its scope is different 
      const result = await axios.post("/api/add/user", {
        //  The parameters passed in are the title bar and content bar in the label 
        title: this.title,
        content: this.content,
      });
      //  Reload the data 
      console.log(result);
      this.getData();
      //  Empty the contents after entering 
      this.title = "";
      this.content = "";
    },

    handleSizeChange(val) {
      console.log(` each page  ${val}  strip `);
      this.pagesize = val;
      this.getData();
      console.log(this.pagesize);
    },
    handleCurrentChange(val) {
      console.log(` The current page : ${val}`);
      this.pageindex = val;
      this.getData();
    },
  },
};
</script>

<style>
</style>

moke/index.js part

//  Use  Mock
import Mock from 'mockjs'
const data = Mock.mock({
    //  attribute  list  The value of is an array , It contains  1  To  10  Elements 
    'list|20-60': [{
        //  attribute  id  It's a self increasing number , The starting value is  1, Every time  1
        "id": '@increment()',
        "title": "@ctitle",
        "content": "@cparagraph",
        "add_time": "@date(yyyy-MM-dd hh:mm:ss)"
    }]
})


const getQuery = (url,name)=>{
  const index = url.indexOf('?')
  console.log(index);
  if(index !== -1) {
    const queryStrArr = url.substr(index+1).split('&')
    for(var i=0;i<queryStrArr.length;i++) {
      const itemArr = queryStrArr[i].split('=')
      console.log(itemArr)
      if(itemArr[0] === name) {
        return itemArr[1]
      }
    }
  }
}

/* //  Output results 
// console.log(JSON.stringify(data,null,4))
Mock.mock(/\/api\/get\/user/,'get',(options)=>{
  console.log(options);
  return {
      status: 200,
      message: ' Get news list data successfully ',
      list:data.list,
      total:data.list.length
  }
}) */

//  A list of data with paging , If there are parameters to be accepted, use regular matching 
// /api/get/news?pageindex=1&pagesize=10
Mock.mock(/\/api\/get\/user/, 'get', (options) => {
  console.log(options)
  //  Get the parameters passed pageindex
  const pageindex = getQuery(options.url,'pageindex')
  //  Get the parameters passed pagesize
  const pagesize = getQuery(options.url,'pagesize')
  //  The starting position of intercepted data 
  const start = (pageindex-1)*pagesize
  //  The end position of intercepted data 
  const end = pageindex*pagesize
  //  Calculate the total number of pages 
  const totalPage = Math.ceil(data.list.length/pagesize)
  //  The starting position of the data :(pageindex-1)*pagesize   End of data :pageindex*pagesize
  const list = pageindex>totalPage?[]:data.list.slice(start,end)

  return {
    status: 200,
    message: ' Get news list successfully ',
    list: list,
    total: data.list.length
  }
})
//  Delete through post request 
Mock.mock('/api/delete/user','post',(options)=>{
  console.log(options);
  //  To be converted into the form of an object 
  // const body = options.body
  const body = JSON.parse(options.body)
  console.log(body)
  //  If each item id And body Of id When equal , Then delete one row of data 
  const index = data.list.findIndex(item=>item.id === body.id);
  data.list.splice(index,1)
  //  Filtering data 
  return{
      status: 200,
      message: ' Delete successful ',
      list:data.list,
  }
})

//  add to 
Mock.mock('/api/add/user','post',(options)=>{
    console.log(options);
    const body = JSON.parse(options.body)
    data.list.unshift(Mock.mock({
            //  attribute  id  It's a self increasing number , The starting value is  1, Every time  1
            "id": '@increment(1)',
            "title": body.title,
            "content": body.content,
            "add_time": "@date(yyyy-MM-dd hh:mm:ss)"
    }))
    return{
        status: 200,
        message: ' Add success ',
        list:data.list,
    }
})

copyright notice
author[Nanchen_ forty-two],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270124584315.html

Random recommended