vue-cli 里 利用mockjs 实现模拟后台数据并成功请求

1 搭建一个vue-cli项目

2 安装 mockjs      和   mock

   npm install mock -S       npm install mockjs -S

3 在项目的src文件夹下创建一个名为 mock.js 的文件里面填写如下代码:

//引入mockjs
const Mock = require('mockjs')
//使用mockjs模拟数据
Mock.mock('/api/data', (req, res) => {
return {
data: [
{
"id" : 1,
"username": "aaa",
"password": "aaa"
},
{
"id" : 2,
"username": "bbb",
"password": "bbb"
},
{
"id": 3,
"username": "ccc",
"password": "ccc"
}
]
}
})

4 在main.js里引入mock.js文档内容如下:

   require('./mock')

5 安装axios 和 jQuery  并在hello.vue里成功引用 (不会的搜百度)

6 在hello.vue填写如下代码

<template>
<div>
<!-- <router-view></router-view> -->
<ul>
<li v-for="(item,key) in data">{{item}}</li>
</ul>
</div>
</template>
<script>
import $ from 'jquery'
import axios from 'axios'
export default{
data(){
return{
data:[]
}
},
mounted: function(){
this.$axios.get('/api/data').then(res=>{
this.data = res.data;
console.log(data)
})
}
}
</script>

7 npm run dev 启动项目模拟的数据就会被循环出来了 (后期会加上登录用户名密码判断)

原文地址:https://www.cnblogs.com/lccluyan/p/8534426.html