vue2 - mockjs的使用

mockjs官网:http://mockjs.com/

 

1.安装mockjs

npm install mockjs

 

2.创建mock文件夹并且创建index.js

//引入mockjs
import Mock from "mockjs"
//引入数据
import BlogMockData from "../mock/BlogMockData";

//使用自定义插件的方式使mock起作用
export default {
  install(Vue) {
    Mock.mock(/\/api\/getBlogList/,function (options) {
      console.log(options); //{url: 'http://localhost:8080/api/getBlogList', type: 'GET', body: null}
      return BlogMockData.blogList
    });

    Mock.mock(/\/api\/getBlog/,function (options) {
      return BlogMockData.blog
    })
  }
}

 

3.数据模板 BlogMockData.js

import Mock from "mockjs"

let blogMockData = Mock.mock({
  //使用mock语法即可
  "blogList|10": [
    {blogId: "@id",author: "@name"}
  ],
  getBlog: {
    //使用mock语法即可
    blogId: "@id",author: "@name"
  }
})

export default blogMockData

 

4.mian.js 使用mock

//使用mock
import mock from "./mock/index.js"
Vue.use(mock)

 

posted on 2023-03-24 23:48  Mikasa-Ackerman  阅读(247)  评论(0编辑  收藏  举报

导航