EDITORIAL words:
Self-Vue, a handwritten json data, is to see my colleagues, ask me how you do not mock, suddenly I felt too far behind
Never stop learning
Ah ah ah
Immediately started to learn mock, really convenient
Learning process or encountered many problems, finally figured out, in this record, to prevent myself to forget
——————————————————————————————————————————————————————————
First, install mock
npm install mockjs --save-dev
Second, Examples (give a small chestnut)
1, a new mock folder, which is created index.js, table.js
Contents are as follows:
2, the introduction of the mock in main.js
import '@/mock/index.js';
3, the following code written in mock / index.js of:
mockjs from Import 'mockjs' ;
Import TableApi from './table.js' @ incorporated generated data JS
const Mock = the require ( 'mockjs') // Mock function
// use blocking rules intercept request hits
Mock.mock ( 'API / getTableData', 'GET' , TableApi.getTableData); // components consistent with the url to be used herein requested data url
Export default mockjs
4, the following code is written in mock / table.js in
import { Random } from 'mockjs'
const code = 200 // 状态码 项目同一
export default{
getTableData () {
let data = []
Array.apply(null, { length: 10 }).forEach(_ => {
data.push({
name: Random.cname(), // 随机汉语名
title: Random.csentence(8, 16), // 随机中文字符串
date: Random.date() // 随机日期
})
})
return {
code,
data
}
}
}
·
5、在需要引入数据的组件内写如下代码(此处html使用了element)
<template>
<el-table
:data="tableData"
style="width: 100%">
<el-table-column
prop="date"
label="日期"
width="180">
</el-table-column>
<el-table-column
prop="name"
label="姓名"
width="180">
</el-table-column>
<el-table-column
prop="title"
label="地址">
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: []
}
},
mounted(){
this.createTable();
},
created(){
//组件实例创建完成,此时dom还未生成
},
methods:{
createTable(){
let $this = this;
// getTableData(data)
this.$axios.get('api/getTableData') //此处地址为mock/index.js文件中.mock函数中的路径
.then(response => {
let $data = response.data.data;
$this.tableData = $data;
})
}
}
}
</script>
6、npm run dev运行,效果如下图