vue2+axios 增删改查

vue2.0以后vue-resource已经不再更新,尤大大也说不再推荐,开始推荐axios,这两天学了一下axios,整理了一套增删改查 
 
以下是官网介绍的一些axios内容

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
axios特色:
从浏览器中创建 XMLHttpRequests
从 node.js 创建 http 请求
支持 Promise API
拦截请求和响应
转换请求数据和响应数据
取消请求
自动转换 JSON 数据
客户端支持防御 XSRF
axios支持的浏览器:


安装
使用 npm: $ npm install axios --save 
使用 bower: $ bower install axios 
使用 cdn: <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

详细的可以参考axios的api https://www.kancloud.cn/yunye/axios/234845

下面开始说我写的这个demo

这个是文件结构 那个ABCD是写的一个小的vuex demo 我就直接在那基础上写了 并不关联

主要就是user.vue 以及 api.js这两个文件

首先来说一下api.js的基本设置

import axios from 'axios'
import qs from 'qs'

axios.defaults.timeout = 5000
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.params = {}

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return res;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
那个params是后面需要用的对象参数,我就直接在前面说明了

然后开始封装增删改查四个函数

//封装获取数据
export const oGet = (url, params) => {
    return new Promise((resolve, reject) => {
        axios.get(url, params)
            .then(res => {
                resolve(res.data)
            }, err => {
                reject(err)
            }).catch(err => {
                reject(err)
            })
    })
};
//封装发送数据
export const oPost = (url, params) => {
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(res => {
                resolve(res.data)
            }, err => {
                reject(err)
            }).catch(err => {
                reject(err)
            })
    })
}
//封装修改数据
export const oUpdate = (url ,param,params) => {
    return new Promise((resolve , reject) => {
        axios.patch(url ,param, params)
            .then(res => {
                resolve(res.data)
            }, err => {
                reject(err)
            }).catch(err => {
                reject(err)
            })
    })
}
//封装删除数据
export const oRemove = (url , params) => {
    return new Promise((resolve,reject) => {
        axios.delete(url,params)
            .then(res => {
                resolve(res.data)
            },err => {
                reject(err)
            }).catch(err => {
                reject(err)
            })
    })
}
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
其中只有修改数据多了一个参数,因为我们后台api给出的是按照id查询然后修改

然后开始说一下user.vue结构 
其中大部分结构和我那篇vue-resource文件一样,只有在增删改查的时候用axios代替了vur-resource

<template>
    <div id="user">
        <el-row class="line-display">
            <el-col :span="22" :offset="1">
                <div class="grid-content" style="margin-top:30px;">
                    <!-- 查询 -->
                    <ul class="btn-edit fl">
                        <li class="input-search">
                            <el-input :placeholder="placeholder" v-model="keywords" style="width: 300px;">
                                <el-select v-model="select" @change="searchFieldChange" slot="prepend">
                                    <el-option label="用户名" value="username"></el-option>
                                    <el-option label="姓名" value="name"></el-option>
                                    <el-option label="电话" value="phone"></el-option>
                                </el-select>
                                <el-button type="danger" class="danger" slot="append" icon="search" @click="query"></el-button>
                            </el-input>
                        </li>
                    </ul>
                    <!-- 操作 -->
                    <ul class="btn-edit fr">
                        <li >
                            <el-button type="primary" @click="dialogCreateVisible = true"> <i class="el-icon-plus iconss" ></i>添加用户</el-button>
                            <el-button type="danger" icon="delete" :disabled="selected.length==0" @click="removeUsers()"  >删除</el-button>
                            <el-button type="warning" @click="enabledUsers(false)" :disabled="selected.length==0" > <i class="el-icon-close iconss" ></i>停用</el-button>
                            <el-button type="success" @click="enabledUsers(true)"  :disabled="selected.length==0" ><i class="el-icon-check iconss" ></i>激活</el-button>
                        </li>
                    </ul>
                    <!-- 用户列表-->
                    <el-col :span="24" style="height:20px;"></el-col>
                    <el-table :data="users"
                              stripe
                              v-loading="loading"
                              element-loading-text="拼命加载中..."
                              style="width: 100%;margin-top:20px;"
                              height="443"
                              @sort-change="tableSortChange"
                              @selection-change="tableSelectionChange" >
                        <el-table-column type="selection"
                                         width="60">
                        </el-table-column>
                        <el-table-column sortable="custom"
                                         prop="username"
                                         label="用户名"
                                         width="100">
                        </el-table-column>
                        <el-table-column prop="name"
                                         label="姓名"
                                         width="80">
                        </el-table-column>
                        <el-table-column prop="phone"
                                         label="手机">
                        </el-table-column>
                        <el-table-column prop="email"
                                         label="邮箱">
                        </el-table-column>
                        <el-table-column prop="create_time" sortable="custom" 
                                         label="注册日期">

                        </el-table-column>
                        <el-table-column
                            prop="is_active"
                            label="状态"
                            width="75"
                            inline-template>
                            <el-tag :type="row.is_active === true ? 'primary' : 'success'" close-transition>{{row.is_active|isEnabledFormatter}}</el-tag>
                        </el-table-column>
                        <el-table-column
                            inline-template
                            label="操作"
                            width="250">
                            <span>
                                <el-button type="danger" size="small" @click="removeUser(row)">删除</el-button>
                                <el-button type="success" size="small" @click="setCurrent(row)">编辑</el-button>
                            </span>
                        </el-table-column>
                    </el-table>
                    <div style=" width:100%; ovflow:hidden; height:40px;"></div>
                    <!--分页begin-->
                    <el-pagination class="tc mg"
                                   :current-page="filter.page"
                                   :page-sizes="[10, 20, 50]"
                                   :page-size="filter.per_page"
                                   layout="total, sizes, prev, pager, next, jumper"
                                   :total="total_rows"
                                   @size-change="pageSizeChange"
                                   @current-change="pageCurrentChange">
                    </el-pagination>
                    <!--分页end-->
                </div>
            </el-col>
        </el-row>
        <!-- 创建用户 begin-->
        <el-dialog title="创建用户" v-model="dialogCreateVisible" :close-on-click-modal="false" :close-on-press-escape="false" @close="reset" >
            <el-form id="#create" :model="create" :rules="rules" ref="create" label-width="100px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="create.username"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="create.name"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="create.password" type="password" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass">
                    <el-input v-model="create.checkPass" type="password"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="create.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="create.email"></el-input>
                </el-form-item>
                <el-form-item label="是否启用">
                    <el-switch on-text="" off-text="" v-model="create.is_active"></el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogCreateVisible = false">取 消</el-button>
                <el-button type="primary" :loading="createLoading" @click="createUser">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 修改用户 begin-->
        <el-dialog title="修改用户信息" v-model="dialogUpdateVisible"  :close-on-click-modal="false" :close-on-press-escape="false">
            <el-form id="#update" :model="update" :rules="updateRules" ref="update" label-width="100px">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="update.name"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="update.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="update.email"></el-input>
                </el-form-item>
                <el-form-item label="是否启用">
                    <el-switch on-text="" off-text="" v-model="update.is_active"></el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogUpdateVisible = false">取 消</el-button>
                <el-button type="primary" :loading="updateLoading" @click="updateUser">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {
        mapState,
        mapMutations,
        mapGetters,
        mapActions
    } from 'vuex';
    import api from '../api/api.js'
    var placeholders = {
        "name": "请输入查找姓名",
        "username": "请输入查找用户名",
        "phone": "请输入查找电话"
    };
    function getuuid() {
        var uid = [];
        var hexDigits = "0123456789abcdefghijklmnopqrst";
        for (var i = 0; i < 32; i++) {
            uid[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        uid[6] = "4";
        uid[15] = hexDigits.substr((uid[15] & 0x3) | 0x8, 1);
        var uuid = uid.join("");
        return uuid;
    }
    export default {
        name:'',
        data : function () {
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.create.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return{
                //url:'http://192.168.1.190/api/v1/accounts',
                users:[],
                filter: {
                    per_page: 10, // 页大小
                    page: 1, // 当前页
                    name: '',
                    username: '',
                    phone: '',
                    is_active: '',
                    create_time:'',
                    sorts: ''
                },
                create: {
                    id: '',
                    username: '',
                    name: '',
                    password: '',
                    checkPass: '',
                    phone: '',
                    email: '',
                    is_active: true
                },
                currentId: '',
                update: {
                    name: '',
                    phone: '',
                    email: '',
                    is_active: true
                },
                rules: {
                    name: [{
                        required: true,
                        message: '请输入姓名',
                        trigger: 'blur'
                    }, {
                        min: 3,
                        max: 15,
                        message: '长度在 3 到 15 个字符'
                    }],
                    username: [{
                        required: true,
                        message: '请输入用户名',
                        trigger: 'blur'
                    }, {
                        min: 3,
                        max: 25,
                        message: '长度在 3 到 25 个字符'
                    }, {
                        pattern: /^[A-Za-z0-9]+$/,
                        message: '用户名只能为字母和数字'
                    }],
                    password: [{
                        required: true,
                        message: '请输入密码',
                        trigger: 'blur'
                    }, {
                        min: 6,
                        max: 25,
                        message: '长度在 6 到 25 个字符'
                    }],
                    checkPass: [{
                        required: true,
                        message: '请再次输入密码',
                        trigger: 'blur'
                    }, {
                        validator: validatePass
                    }],
                    email: [{
                        type: 'email',
                        message: '邮箱格式不正确'
                    }],
                    phone: [{
                        pattern: /^1[34578]\d{9}$/,
                        message: '请输入中国国内的手机号码'
                    }]
                },
                updateRules: {
                    name: [{
                        required: true,
                        message: '请输入姓名',
                        trigger: 'blur'
                    }, {
                        min: 3,
                        max: 15,
                        message: '长度在 3 到 15 个字符'
                    }],
                    email: [{
                        type: 'email',
                        message: '邮箱格式不正确'
                    }],
                    phone: [{
                        pattern: /^1[34578]\d{9}$/,
                        message: '请输入中国国内的手机号码'
                    }]
                },
                total_rows:0,
                loading:true,
                keywords: '', //搜索框的关键字内容
                select: 'username', //搜索框的搜索字段
                selected: [], //已选择项
                dialogCreateVisible: false, //创建对话框的显示状态
                dialogUpdateVisible: false, //编辑对话框的显示状态
                createLoading: false,
                updateLoading: false,
                placeholder: placeholders["username"]
            }
        },
        mounted:function(){
            this.getUsers();
        },
        methods:{

            tableSelectionChange(val) {
                this.selected = val;
            },
            //排序
            tableSortChange(val) {
                if (val.prop != null) {
                    if (val.order == 'descending') {
                        this.filter.sorts = '-' + val.prop;
                    } else {
                        this.filter.sorts = '' + val.prop;
                    }
                } else {
                    this.filter.sorts = '';
                }
                this.getUsers();
            },
            //每页显示多少条
            pageSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.filter.per_page = val;
                this.getUsers();
            },
            //当前页选择
            pageCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.filter.page = val;
                this.getUsers();
            },
             searchFieldChange(val) {
                this.placeholder = placeholders[val];
                console.log(`搜索字段: ${val} `);
            },
             rowClick(row, event) {
                var index = $.inArray(row, this.selected)
                if (index < 0) {
                    this.selected.push(row);
                    this.$refs.usersTable.toggleRowSelection(row, true);
                } else {
                    this.selected.splice(index, 1);
                    this.$refs.usersTable.toggleRowSelection(row, false);
                }
            },
           // 重置表单
            reset() {
                this.$refs.create.resetFields();
            },
            setCurrent(user) {
                this.currentId = user.id;
                this.update.name = user.name;
                this.update.phone = user.phone;
                this.update.email = user.email;
                this.update.is_active = user.is_active;
                this.dialogUpdateVisible = true;
            },
            //获取用户数据
            getUsers(){
                this.loading = true;
                api._get().then(res => {
                    this.users = res.datas;
                    this.total_rows = res.total_rows;
                    this.loading=false;
                },err => {
                    console.log(err);
                })
            },
            //创建用户
            createUser() {
                this.$refs.create.validate((valid) => {
                    if (valid) {
                        this.create.id = getuuid();
                        this.createLoading = true;
                        api._post(this.create).then(res => {
                            this.$message.success('创建用户成功!');
                            this.dialogCreateVisible = false;
                            this.createLoading = false;
                            this.reset();
                            this.getUsers();
                        }).catch((res) => {
                            var data = res.datas;
                            if (data instanceof Array) {
                              this.$message.error(data[0]["message"]);
                            } else if (data instanceof Object) {
                              this.$message.error(data["message"]);
                            }
                            this.createLoading = false;
                        });
                    } else {
                      //this.$message.error('存在输入校验错误!');
                      return false;
                    }
                });
            },

            // 更新用户资料
            updateUser() {
                this.$refs.update.validate((valid) => {
                    if (valid) {
                        this.updateLoading = true;
                        api._update(this.currentId, this.update).then(res => {
                            this.$message.success('修改用户资料成功!');
                            this.dialogUpdateVisible = false;
                            this.updateLoading = false;
                            this.getUsers();
                        }).catch((res) => {
                            var data = res.datas;
                            if (data instanceof Array) {
                                this.$message.error(data[0]["message"]);
                            } else if (data instanceof Object) {
                                this.$message.error(data["message"]);
                            }
                            this.updateLoading = false;
                          });
                    } else {
                        return false;
                    }
                });
            },

            // 删除单个用户
            removeUser(user) {

                this.$confirm('此操作将永久删除用户 ' + user.username + ', 是否继续?', '提示', {
                  type: 'warning'
                }).then(() => {
                    api._remove(user).then(res => {
                        this.$message.success('成功删除了用户' + user.username + '!');
                        this.getUsers();
                        console.log(user.id);
                    }).catch((res) => {
                        this.$message.error('删除失败!');
                    });
                }).catch(() => {
                    this.$message.info('已取消操作!');
                });
            },

             //删除多个用户
            removeUsers(ids) {
                var ids = [];
               $.each(this.selected, (i, users) => {
                    ids.push(users.id);
                });
                ids = ids.join(",");
                this.$confirm('此操作将永久删除 ' + this.selected.length + ' 个用户, 是否继续?', '提示', {
                    type: 'warning'
                }).then(() => {
                    api._removes(ids).then(res =>{
                        this.$message.success('删除了' + this.selected.length + '个用户!');
                        this.getUsers();
                    }).catch((res) => {
                        this.$message.error('删除失败!');
                    });
                }).catch(() => {
                    this.$message('已取消操作!');
                });
            }

        }
    }
</script>
<style>
ul li{list-style: none}
.tc{text-align:center; }
.mg{ margin-top:10px;}
.fl{float:left}
.fr{float:right}
</style>
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
我单独把各个函数拎出来说一下

**

获取数据
** 
首先,我在api.js调用了一下oGet函数

export default {
    _get () {
        return oGet('http://192.168.1.190/api/v1/accounts');
    },
}
1
2
3
4
5
然后user.vue中调用_get()函数

//获取用户数据
getUsers(){
    this.loading = true;
    api._get().then(res => {
        this.users = res.datas;
        this.total_rows = res.datas.total_rows;
        this.loading=false;
        console.log(res);
    },err => {
        console.log(err);
    })
},
1
2
3
4
5
6
7
8
9
10
11
12
删除数据
删除包括单条删除以及多条删除 
单条删除 需要获取id,所以传了一个参数,然后在地址上拼接id 
多条删除 将选中的id 放到数组里面,拼接地址

 _remove(user){
        var userid = user.id;
        return oRemove('http://192.168.1.190/api/v1/accounts/'+ userid);

    },

_removeUsers(param){
        return oRemove(apiTool+'api/v1/accounts/'+'?ids='+param);
    },
1
2
3
4
5
6
7
8
9
然后

// 删除单个用户
removeUser(user) {

    this.$confirm('此操作将永久删除用户 ' + user.username + ', 是否继续?', '提示', {
      type: 'warning'
    }).then(() => {
        api._remove(user).then(res => {
            this.$message.success('成功删除了用户' + user.username + '!');
            this.getUsers();
            console.log(user.id);
        }).catch((res) => {
            this.$message.error('删除失败!');
        });
    }).catch(() => {
        this.$message.info('已取消操作!');
    });
},

//删除多个用户
removeUsers(ids) {
    var ids = [];
   $.each(this.selected, (i, users) => {
        ids.push(users.id);
    });
    ids = ids.join(",");
    this.$confirm('此操作将永久删除 ' + this.selected.length + ' 个用户, 是否继续?', '提示', {
        type: 'warning'
    }).then(() => {
        api._removes(ids).then(res =>{
            this.$message.success('删除了' + this.selected.length + '个用户!');
            this.getUsers();
        }).catch((res) => {
            this.$message.error('删除失败!');
        });
    }).catch(() => {
        this.$message('已取消操作!');
    });
}
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
增加数据
_post (params) {
        return oPost('http://192.168.1.190/api/v1/accounts',params);
    },
1
2
3
然后user.vue

//创建用户
createUser() {
    this.$refs.create.validate((valid) => {
        if (valid) {
            this.create.id = getuuid();
            this.createLoading = true;
            api._post(this.create).then(res => {
                this.$message.success('创建用户成功!');
                this.dialogCreateVisible = false;
                this.createLoading = false;
                this.reset();
                this.getUsers();
            }).catch((res) => {
                var data = res;
                if (data instanceof Array) {
                  this.$message.error(data[0]["message"]);
                } else if (data instanceof Object) {
                  this.$message.error(data["message"]);
                }
                this.createLoading = false;
            });
        } else {
          //this.$message.error('存在输入校验错误!');
          return false;
        }
    });
},
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
修改数据
传两个参数,param用来拼接ids,params传递修改的对象

_update (param,params) {
        return oUpdate('http://192.168.1.190/api/v1/accounts'+'?ids='+param, params);
    },
1
2
3
然后

// 更新用户资料
updateUser() {
    this.$refs.update.validate((valid) => {
        if (valid) {
            this.updateLoading = true;
            api._update(this.currentId, this.update).then(res => {
                this.$message.success('修改用户资料成功!');
                this.dialogUpdateVisible = false;
                this.updateLoading = false;
                this.getUsers();
            }).catch((res) => {
                var data = res;
                if (data instanceof Array) {
                    this.$message.error(data[0]["message"]);
                } else if (data instanceof Object) {
                    this.$message.error(data["message"]);
                }
                this.updateLoading = false;
              });
        } else {
            return false;
        }
    });
},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
不太会写 可能看起来有点混乱 
贴个地址 
https://github.com/janessssss/vue-axios
--------------------- 
作者:janessssss 
来源:CSDN 
原文:https://blog.csdn.net/janessssss/article/details/78228279 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值