1.在项目根目录创建一个data.json
{
"personnel":
[
{ "id":1, "name": "张三", "sex": "男" },
{ "id":2, "name": "王五", "sex": "男" },
{ "id":3, "name": "小丽", "sex": "女" },
{ "id":4, "name": "小莉", "sex": "女" }
]
}
2.在项目目录的build目录下,找到webpack.dev.conf进行修改
const express = require('express')
const app = express()//请求server
var appData = require('../data.json')//加载本地数据文件
var personnel = appData.personnel;//获取对应的本地数据
var apiRoutes = express.Router() ;
app.use('/api', apiRoutes)//通过路由请求数据
然后在webpack.dev.conf中找到devServer:{}加上before()方法
before(app) {
app.get('/api/personnel', (req, res) => {
res.json({
data: personnel
})//接口返回json数据,上面配置的数据personnel就赋值给data请求后调用
})
}
3.用vue-resource向服务器请求数据
安装之后在main.js引入vue-resource
4.App.vue
<template>
<div id="app">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">员工列表</h3>
</div>
<div class="panel-body form-inline">
<label>
Name:
<input type="text" name="" class="form-control">
</label>
<input type="button" name="" value="添加" class="btn btn-primary" @click="add">
</div>
</div>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Sex</th>
<th>Operation</th>
</tr>
</thead>
<tbody>
<tr v-for="item in list " :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.sex}}</td>
<td><a href="">删除</a></td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
name: 'App',
data: function () {
return {
list:[]
}
},
created () {//当vm实例的data和methods初始化完毕后,vm实例会自动执行created这个生命周期
this.getAllList ();
},
methods: {
add () {},
getAllList () {//获取所有的车品牌列表
//分析
//直接this.$http来发起数据请求
//根据接口API文档,获取列表的时候,应该发起一个get请求
//$this.$http.get('url').then(function(result){})
//当通过then指定回调函数之后,在回调函数中,可以拿到数据服务器返回的result
this.$http.get('/api/personnel').then( (result)=> {
// 通过$http获取到的数据,都在
this.list = result.body.data
})
}
}
}
</script>
记得重新 npm run dev