簡述
由于后端與前端同時開發(fā),而后端接口還未開發(fā)完成,前端又急需數(shù)據(jù)進(jìn)行測試。那么mock模擬數(shù)據(jù)就是很好的選擇,當(dāng)然還有其他方式,以下做一個mock模擬數(shù)據(jù)示例,供參考學(xué)習(xí)。
前期準(zhǔn)備
1.此示例中用到了elementUI(安裝引入方式可移步到我的其他文章)
2.axios插件
安裝
npm install --save axios vue-axios
或
npm install axios
在main.js中引入
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
使用方式
Vue.axios.get(api).then((response) => {
console.log(response.data)
})
this.axios.get(api).then((response) => {
console.log(response.data)
})
this.$http.get(api).then((response) => {
console.log(response.data)
})
3.mock插件
安裝
npm install mockjs
或者
npm install --save mockjs
(安裝腳手架cli可使用)或者
cnpm install --save mockjs
編寫數(shù)據(jù)
1.創(chuàng)建文件夾
a.在src下面創(chuàng)建一個mock文件夾
b.在mock文件夾的下創(chuàng)建data文件夾(存放數(shù)據(jù))
2.編寫數(shù)據(jù)文件
a.在mock文件夾下創(chuàng)建index.js文件來寫代碼
b.data文件夾下創(chuàng)建home.json文件用來放返回來的數(shù)據(jù)
3.編寫模擬數(shù)據(jù)
圖示

圖示數(shù)據(jù)
源碼:
{
"msg":"測試接口數(shù)據(jù)成功!",
"data":[
{"name":"abc","sex":"男", "age":"15","home":"北京"},
{"name":"123","sex":"男","age":"20","home":"湖南"},
{"name":"qwe","sex":"女","age":"25","home":"北京"},
{"name":"wer","sex":"男","age":"30","home":"天津"},
{"name":"sdf","sex":"女","age":"45","home":"上海"}
]
}
引入mock
在mock文件夾下的index.js中引入

引入數(shù)據(jù)文件
源碼:
// 引入ANGLE_instanced_arrays
var Mock=require("mockjs")
// 請求地址,請求方法(post/get),require(請求數(shù)據(jù)地址)
Mock.mock("/test/user","get",require("./data/home.json"))
入口文件中引入
在main.js中引用mock
//引用mock
//名字默認(rèn)寫index.js,在引入的時候就可以不用寫文件名
//require(".mock/index.js")
//mock里面默認(rèn)請求index.js
require("./mock")

圖示
請求數(shù)據(jù)
1.局部引用:單獨頁面請求數(shù)據(jù),渲染當(dāng)前頁
2.全局引用:在main.js中引入
// 全局引用axios
import axios from "axios"
Vue.prototype.$axios=axios
創(chuàng)建組件
<template>
<!-- 測試mock數(shù)據(jù) -->
<el-table :data="testDatas" stripe style="width: 100%">
<el-table-column prop="name" label="姓名" width="180">
</el-table-column>
<el-table-column prop="sex" label="性別" width="180">
</el-table-column>
<el-table-column prop="age" label="年齡">
</el-table-column>
<el-table-column prop="home" label="家庭住址">
</el-table-column>
</el-table>
</template>
<script>
export default{
data(){
return{
testDatas: []
}
},
// 鉤子函數(shù),頁面加載完成請求數(shù)據(jù)
created() {
this.$axios({
url:"/test/user", //請求地址
method:"get" //請求方式
}).then(ok =>{
// ok表示請求成功的數(shù)據(jù)
console.log(ok)
// 把請求到的數(shù)據(jù)給testDatas數(shù)組
this.testDatas=ok.data.data
});
}
}
</script>
<style>
</style>
特別提醒:
由于在此使用了elementui運行時報錯
最初賦值數(shù)據(jù)如下:
this.testDatas=ok.data
報錯:
Error in render: "TypeError: data.reduce is not a function"
解決方式:
在請求數(shù)據(jù)給數(shù)組時要加data
// 把請求到的數(shù)據(jù)給testDatas數(shù)組
this.testDatas=ok.data.data
效果顯示:

效果圖