目录结构
需要新建、修改的文件或文件夹
新建:src/mock、src/mock/mock.js、src/static/data.json
修改:src/components/HelloWorld.vue、src/main.js
安装组件
$ 安装mock.js
npm install mockjs
$ 安装axios
npm install axios
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
import './mock/mock.js'
Vue.prototype.$http = axios
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
mock.js
import Mock from 'mockjs'
const Random = Mock.Random
const produceData = function (opt) {
console.log('opt:', opt)
let articles = []
for (let i = 0; i < 5; i++) {
let newArticleObject = {
name: Random.cname(),
date: Random.date() + '' + Random.time(),
email: Random.email()
}
articles.push(newArticleObject)
}
return {
data: articles
}
}
Mock.mock('/user.json', /post|get/i, produceData)
data.json
{
"data": [
{ "name":"卢禹轩"},
{ "name":"刘雨铮"},
{ "name":"沙徐"}
]
}
HelloWorld.vue
<template>
<div class="hello">
<h1></h1><br>
<h2></h2>
<ul>
<li v-for = "(item,index) in data" :key = "index">,,</li>
</ul>
<h2></h2>
<ul>
<li v-for = "(item,index) in jsonData" :key = "index+10"></li>
</ul>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'vue.js axios mock.js使用示例',
msg1: 'axios获取mock.js自动生成json示例',
msg2: 'axios获取本地json文件示例',
data: [],
jsonData: []
}
},
mounted: function () {
this.getAlldata()
this.getData()
},
methods: {
getAlldata () {
let that = this
this.$http.get('/user.json')
.then(res => {
console.log('mock.js连接成功')
console.log('res:', res)
that.data = res.data.data
})
.catch(err => {
console.log('mock.js连接错误' + err)
})
},
getData () {
let _that = this
this.$http.get('../../static/json/data.json')
.then(res => {
console.log('data.json连接成功')
console.log('res:', res.data)
_that.jsonData = res.data.data
})
.catch(err => {
console.log('data.json连接错误' + err)
})
}
}
}
</script>
<style scoped>
</style>
运行示例
cd frontend
npm run dev