第一种简单使用
①新建一个json文件
{
"student":[
{"name":"111","age":"1"},
{"name":"222","age":"2"},
{"name":"333","age":"3"}
],
"class":[
{"classname":"111","number":"10"},
{"classname":"222","number":"20"},
{"classname":"333","number":"30"}
]
}
②在vue.config.js中
const express = require('express')
const app = express()
const appData = require('./src/mock/test.json');
const student = appData.student;
const class_student = appData.class;
module.exports = {
devServer: {
before(app){
app.get('/api/student',function (req,res) {
res.json({
errno:0,
data:student
})
});
app.get('/api/goods', function(req, res) {
res.json({
errno: 0,
data: class_student
})
});
}
}
}
③直接在页面中使用
axios.get('http://localhost:8080/api/student').then(response =>{
console.log(response.data)
},response =>{
console.error("error")
})
第二种规范使用
①新建js文件模拟数据
import Mock from 'mockjs'
export default{
getName: ()=>({
code:1,
data:{
name:"Tom",
age:"12",
sex:"man"
}
})
}
②定义mock的方法
import Mock from 'mockjs'
import decision from './decision'
// 前台接口方法路径 访问方式 模拟数据的方法
Mock.mock('/decision/getName','get',decision.getName);
// 生成随机数据
Mock.mock('/api/data','get',()=>{ return Mock.mock({name:'@cname',city:'@city(true)'})});
③在main.js中引入定义
import './mock/index'
这里就完成了一半,接下来定义前台请求方法就能够请求到mock里的模拟数据
④在api中定义前台请求方法
import request from 'axios'
export function getName(){
return request({
url:'/decision/getName',
method:'get'
})
}
⑤在页面中使用
import { getName } from '../api/api.js'
export default class HelloWorld extends Vue {
mounted(){
getName().then(response =>{
console.log(response)
})
}
mock随机生成的官网例子
http://mockjs.com/examples.html
网友评论