【vue】vue +element 搭建项目,mock模拟数据(纯干货)

时间:2022-03-26 00:03:20

1.安装mockjs依赖

(c)npm install mockjs --save-dev

【vue】vue +element 搭建项目,mock模拟数据(纯干货)

2.安装axios(Ajax)

(c)npm install --save axios

【vue】vue +element 搭建项目,mock模拟数据(纯干货)

3.项目目录

【vue】vue +element 搭建项目,mock模拟数据(纯干货)

4.设计到的相关文件

fetch.js(封装axios)

import Qs from 'qs';
import axios from 'axios';
// 创建axios实例
const service = axios.create({
baseURL: process.env.BASE_API, // api的base_url
timeout: 5000, // 请求超时时间
withCredentials: true, //跨域
transformRequest: [function (data) {
data = Qs.stringify(data);
return data
}],
}); // request拦截器
service.interceptors.request.use(config => {
config.headers['Accept'] = 'text/plain';
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
const defaultParams = {
version: process.env.VERSION,
platform: 'pcweb',
};
if (config.method == 'post') {
config.data = {
...defaultParams,
...config.data
}
} else if (config.method == 'get') {
config.params = {
...defaultParams,
...config.params
}
}
return config;
}, error => {
console.log(error); // for debug
Promise.reject(error);
}) // respone拦截器
service.interceptors.response.use(
response => {//其他一些(登陆过期等)请自行添加
return response;
},
error => {
return Promise.reject(error);
}); export default service;

api/skill/index.js(接口定义)

import fetch from '@/utils/fetch';

export function departmentList(params) {
return fetch({
url: '/skill/list',
method: 'get',
params: params || {}
});
}

mock/news.js(模拟数据)

import Mock from 'mockjs';
// 获取 mock.Random 对象
const Random = Mock.Random;
// mock一组数据
const produceNewsData = function () {
let articles = [];
for (let i = 0; i < 100; i++) {
let newArticleObject = {
title: Random.csentence(5, 30), // Random.csentence( min, max )
thumbnail_pic_s: Random.dataImage('300x250', 'mock的图片'), // Random.dataImage( size, text ) 生成一段随机的 Base64 图片编码
author_name: Random.cname(), // Random.cname() 随机生成一个常见的中文姓名
date: Random.date() + ' ' + Random.time() // Random.date()指示生成的日期字符串的格式,默认为yyyy-MM-dd;Random.time() 返回一个随机的时间字符串
}
articles.push(newArticleObject)
} return {
articles: articles
}
}
export default {
getexamUploder: () => produceNewsData(),
};

在main.js

import '@/mock/index.js';  // 使用mockjs模拟

mock/index.js

import Mock from 'mockjs';
import treeAPI from './news'; Mock.mock(/\/skill\/list/, 'get', treeAPI.getexamUploder);
export default Mock;

view/skill/tree.vue

import { departmentList } from '@/api/skill/index';//引入接口
getList(){
let data = {
pid: 0,
}
departmentList(data).then(response => {//接口调用
console.log(response.data);
});
},

5.效果图:

【vue】vue +element 搭建项目,mock模拟数据(纯干货)

相关资料:

作者:smile.轉角

QQ:493177502