1.什么是mockjs
前端编写代码的时候,可以用mockjs来生成随机数据,拦截 Ajax 请求。
2.使用mockjs
①利用vue-cli创建项目
npm i create vue-mock
②安装mockjs和axios,进入到项目文件夹中
npm i mockjs
npm i axios
③在src中创建mock文件夹并建立index.js文件

④index.js文件中
import Mock from 'mockjs' //引入mockjs
//拦截请求,具体语法下面给出帮助文档
Mock.mock('/list/index',{
'list|5':[
{
'name':'@cname'
}
]
})
具体语法规则请看:帮助文档
⑤main.js文件中
import Vue from 'vue'
import App from './App.vue'
import './mock' //必须引入mock文件夹下的文件,这样mockjs才可以拦截到请求
import axios from 'axios'
Vue.prototype.$axios = axios; //把axios挂载到vue原型上,这样所有的vue对象都可以使用
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
⑥App.vue文件中
<template>
<div id="app">
{{text}}
</div>
</template>
<script>
export default {
name: 'app',
components: {
},
data() {
return {
text:[]
}
},
mounted() {
this.getData();
},
methods: {
getData:function(){
console.log(111)
var that = this; //用that去保存vue的实例
that.$axios.get('/index').then(function (res) {
that.text = res.data.list
console.log(res);
})
}
},
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
tip:今天遇到个问题,我用vscode编译console.log会报错。研究了一下,原来是es6语法配置的问题,在项目里要找到package.json配置文件,然后在找到"rules":{}这个配置项,在里面添加"no-console":"off"。因为更改了配置文件,所以重启一下项目,ok完美解决。
"rules": {
"no-console":"off"
}
网友评论