vue(3)
这篇文章主要讲利用vue-resource
结合json-server
实现模拟请求后台操作用户数据,实现增删改查。
1. vue-resource
vue-resource插件具有以下特点:
a. 体积小
vue-resource非常小巧,在压缩以后只有大约12KB,服务端启用gzip压缩后只有4.5KB大小,这远比jQuery的体积要小得多。
b. 支持主流的浏览器
和Vue.js一样,vue-resource除了不支持IE 9以下的浏览器,其他主流的浏览器都支持。
c. 支持Promise API和URI Templates
Promise是ES6的特性,Promise的中文含义为“先知”,Promise对象用于异步计算。
URI Templates表示URI模板,有些类似于ASP.NET MVC的路由模板。
d. 支持拦截器
拦截器是全局的,拦截器可以在请求发送前和发送请求后做一些处理。
拦截器在一些场景下会非常有用,比如请求发送前在headers中设置access_token,或者在请求失败时,提供共通的处理方式。
vue-resource
+jsonplaceholder
模拟请求后台获取用户数据- 测试地址
http://jsonplaceholder.typicode.com/users
2. vue-resource
+ json-server
模拟请求后台操作数据
2.1 安装
json-server
1
2
3
4
5在任意目录 全局安装json-server
npm install json-server -g
安装完成后检查是否全局安装成功
json-server -h2.2 安装成功后命令行出现以下界面标识安装成功
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29D:\vue-program>json-server -h
bin.js [options] <source>
Options:
--config, -c Path to config file [default: "json-server.json"]
--port, -p Set port [default: 3000]
--host, -H Set host [default: "0.0.0.0"]
--watch, -w Watch file(s) [boolean]
--routes, -r Path to routes file
--middlewares, -m Paths to middleware files [array]
--static, -s Set static files directory
--read-only, --ro Allow only GET requests [boolean]
--no-cors, --nc Disable Cross-Origin Resource Sharing [boolean]
--no-gzip, --ng Disable GZIP Content-Encoding [boolean]
--snapshots, -S Set snapshots directory [default: "."]
--delay, -d Add delay to responses (ms)
--id, -i Set database id property (e.g. _id) [default: "id"]
--foreignKeySuffix, --fks Set foreign key suffix (e.g. _id as in post_id)
[default: "Id"]
--quiet, -q Suppress log messages from output [boolean]
--help, -h Show help [boolean]
--version, -v Show version number [boolean]
Examples:
bin.js db.json
bin.js file.js
bin.js http://example.com/db.json
https://github.com/typicode/json-server2.3 建立
db.json
文件(注意:等下要在这个文件下打开json-server
服务器)1
2
3
4
5
6
7{
"api": [
{"id": 1, "name": "jack", "age":"18" },
{"id": 2, "name": "tom", "age":"8" },
{"id": 3, "name": "jerry", "age":"7" }
]
}2.4 在刚建好的
db.json
文件中打开json-server
服务器1
2
3
4
5注意,如果在执行命令行的文件夹中没有db.json文件,系统会自建一个默认的
json-server --watch db.json
终止服务器
ctrl + c2.5 使用方法
- html部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19<div class="panel-body form-inline">
<label>name:
<input type="text" class="form-control" v-model="name">
</label>
<label>age:
<input type="number" class="form-control" v-model="age">
</label>
<input type="button" class="btn btn-default" value="添加" @click="add">
</div>
<tr v-for="item in list" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>
<a href="#" @click.prevent="edit(item.id)">edit</a>
<a href="#" @click.prevent="del(item.id)">delete</a>
</td>
</tr>- js部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62// 通过全局配置,请求的数据接口 根域名后在每次单独发起 http 请求的时候,
// 请求的 url 路径,应该以相对路径开头,前面不能带 / ,否则 不会启用根路径做拼接;
Vue.http.options.root = 'http://localhost:3000/';
// 全局启用emulateJSON选项
// 以普通表单格式,将数据提交给服务器 application/x-www-form-urlencoded
Vue.http.options.emulateJSON = true;
let vm = new Vue({
el: '#app',
data: {
name: '',
age: '',
list: []
},
created() {// 当vm实例的data和methods初始化完毕后,vm实例会自动执行created()方法
this.getList()
},
methods: {
add() {
// 注意这个api 对应了db.json中的 'api'字段
this.$http.post('api', {name: this.name, age: this.age}).then(res => {
console.log(res);
if (res.status === 201) { // 添加成功状态201
this.getList();
this.name = this.age = '' //添加成功后重置
} else {
alert('添加失败')
}
})
},
getList() {
this.$http.get('api').then(result => {
// console.log(result);
if (result.status === 200) { // success
this.list = result.body
} else {//fail
alert('数据请求失败')
}
})
},
del(id) {
this.$http.delete('api/' + id).then(res => {
//console.log(res);
if(res.status === 200){
this.getList()
}else{
alert('删除失败')
}
})
},
edit(id) {
this.$http.put('api/' + id, {name: 'red', age: 51}).then(res => {
//console.log(res);
if(res.status === 200){
this.getList()
}else{
alert('修改失败')
}
})
}
}
});2.6 备注 –服务器返回数据 console.log(res)