1.npm install mockjs --save
2.在src文件下建mock.js文件
3.mock.js文件文件内容
1 //引入mockjs 2 import Mock from 'mockjs' 3 //使用mockjs模拟数据 4 export default Mock.mock('/api/users', (req, res) => { 5 return Mock.mock({ 6 "user|1-10": [{ 7 'name': '@cname', 8 'id|+1': 1, 9 'age|10-60': 0, //10-60以内的随机数,0用来确定类型 10 'birthday': '@date("yyyy-MM-dd")', //年月日 11 'city': '@city(true)' //中国城市 12 }] 13 }) 14 })
4.写app.vue的template
1 <template> 2 <div id="app"> 3 <el-table :data="users" stripe style="80%" align="center"> 4 <el-table-column prop="name" label="姓名" width="180" align="center"></el-table-column> 5 <el-table-column prop="age" label="年龄" width="180" align="center"></el-table-column> 6 <el-table-column prop="birthday" label="出生日期" width="180" align="center"></el-table-column> 7 <el-table-column prop="city" label="地址" width="180" align="center"></el-table-column> 8 </el-table> 9 </div> 10 </template>
4.写app.vue的script:此前要安装npm install axios
1 <script> 2 import axios from 'axios'; //vue2.x的引入axios进行前后端交互 3 export default { 4 name: 'HelloWorld', 5 data () { 6 return { 7 users: [] 8 } 9 }, 10 mounted: function(){ 11 axios.get('/api/users').then(res=>{ 12 console.log(res) 13 this.users= res.data.user; 14 }) 15 } 16 } 17 18 </script>
5.引入到main.js中
1 import Vue from 'vue'; 2 import ElementUI from 'element-ui'; 3 // import 'element-ui/lib/theme-chalk/index.css'; 4 import App from './App.vue'; 5 import Mock from './mock' 6 7 Vue.use(ElementUI); 8 9 10 new Vue({ 11 el: '#app', 12 render: h => h(App) 13 });