axios-elementui增刪改查小例子巍糯,代碼見(jiàn)github,給加個(gè)星星:
https://github.com/sky-xsk/axios-elementui-
我用的是公司內(nèi)部提供的api尝江,所以不在公司內(nèi)部涉波,是看不到效果的,最主要的還是對(duì)源碼的參考炭序!
放心我會(huì)附上圖片效果的!
之前使用vue-reource寫(xiě)的啤覆,并且沒(méi)有封裝,這個(gè)例子用的是es6里的promise進(jìn)行的封裝少态,單獨(dú)抽取出api接口城侧;
代碼如下:
模板:
<template>
<div id="user">
<h1>vue2.0+axios+elementui 簡(jiǎn)單的增刪改查</h1>
<el-row class="line-display">
<el-col :span="22" :offset="1">
<div class="grid-content" style="margin-top:30px;">
<!-- 操作 -->
<ul class="btn-edit fr">
<li >
<el-button type="primary" @click="dialogCreateVisible = true"> <i class="el-icon-plus iconss" ></i>添加用戶(hù)</el-button>
<el-button type="danger" icon="delete" :disabled="selected.length==0" @click="removeUsers()" >刪除</el-button>
</li>
</ul>
<!-- 用戶(hù)列表-->
<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="用戶(hù)名"
width="100">
</el-table-column>
<el-table-column prop="name"
label="姓名"
width="80">
</el-table-column>
<el-table-column prop="phone"
label="手機(jī)">
</el-table-column>
<el-table-column prop="email"
label="郵箱">
</el-table-column>
<el-table-column prop="create_time" sortable="custom"
label="注冊(cè)日期">
</el-table-column>
<el-table-column
prop="is_active"
label="狀態(tài)"
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>
</div>
</el-col>
</el-row>
<!-- 創(chuàng)建用戶(hù) begin-->
<el-dialog title="創(chuàng)建用戶(hù)" 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="用戶(hù)名" 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="確認(rèn)密碼" 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>
<!-- 修改用戶(hù) begin-->
<el-dialog title="修改用戶(hù)信息" 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>
js代碼:
<script>
import {
mapState,
mapMutations,
mapGetters,
mapActions
} from 'vuex';
import api from '../api/api.js'
var placeholders = {
"name": "請(qǐng)輸入查找姓名",
"username": "請(qǐng)輸入查找用戶(hù)名",
"phone": "請(qǐng)輸入查找電話"
};
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('請(qǐng)?jiān)俅屋斎朊艽a'));
} else if (value !== this.create.password) {
callback(new Error('兩次輸入密碼不一致!'));
} else {
callback();
}
};
return{
users:[],
filter: {
per_page: 10, // 頁(yè)大小
page: 1, // 當(dāng)前頁(yè)
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: '請(qǐng)輸入姓名',
trigger: 'blur'
}, {
min: 3,
max: 15,
message: '長(zhǎng)度在 3 到 15 個(gè)字符'
}],
username: [{
required: true,
message: '請(qǐng)輸入用戶(hù)名',
trigger: 'blur'
}, {
min: 3,
max: 25,
message: '長(zhǎng)度在 3 到 25 個(gè)字符'
}, {
pattern: /^[A-Za-z0-9]+$/,
message: '用戶(hù)名只能為字母和數(shù)字'
}],
password: [{
required: true,
message: '請(qǐng)輸入密碼',
trigger: 'blur'
}, {
min: 6,
max: 25,
message: '長(zhǎng)度在 6 到 25 個(gè)字符'
}],
checkPass: [{
required: true,
message: '請(qǐng)?jiān)俅屋斎朊艽a',
trigger: 'blur'
}, {
validator: validatePass
}],
email: [{
type: 'email',
message: '郵箱格式不正確'
}],
phone: [{
pattern: /^1[34578]\d{9}$/,
message: '請(qǐng)輸入中國(guó)國(guó)內(nèi)的手機(jī)號(hào)碼'
}]
},
updateRules: {
name: [{
required: true,
message: '請(qǐng)輸入姓名',
trigger: 'blur'
}, {
min: 3,
max: 15,
message: '長(zhǎng)度在 3 到 15 個(gè)字符'
}],
email: [{
type: 'email',
message: '郵箱格式不正確'
}],
phone: [{
pattern: /^1[34578]\d{9}$/,
message: '請(qǐng)輸入中國(guó)國(guó)內(nèi)的手機(jī)號(hào)碼'
}]
},
total_rows:0,
loading:true,
keywords: '', //搜索框的關(guān)鍵字內(nèi)容
select: 'username', //搜索框的搜索字段
selected: [], //已選擇項(xiàng)
dialogCreateVisible: false, //創(chuàng)建對(duì)話框的顯示狀態(tài)
dialogUpdateVisible: false, //編輯對(duì)話框的顯示狀態(tài)
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();
},
//每頁(yè)顯示多少條
pageSizeChange(val) {
console.log(`每頁(yè) ${val} 條`);
this.filter.per_page = val;
this.getUsers();
},
//當(dāng)前頁(yè)選擇
pageCurrentChange(val) {
console.log(`當(dāng)前頁(yè): ${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;
},
//獲取用戶(hù)數(shù)據(jù)
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);
})
},
//創(chuàng)建用戶(hù)
createUser() {
this.$refs.create.validate((valid) => {
if (valid) {
this.create.id = getuuid();
this.createLoading = true;
api._post(this.create).then(res => {
this.$message.success('創(chuàng)建用戶(hù)成功!');
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('存在輸入校驗(yàn)錯(cuò)誤!');
return false;
}
});
},
// 更新用戶(hù)資料
updateUser() {
this.$refs.update.validate((valid) => {
if (valid) {
this.updateLoading = true;
api._update(this.currentId, this.update).then(res => {
this.$message.success('修改用戶(hù)資料成功彼妻!');
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;
}
});
},
// 刪除單個(gè)用戶(hù)
removeUser(user) {
this.$confirm('此操作將永久刪除用戶(hù) ' + user.username + ', 是否繼續(xù)?', '提示', {
type: 'warning'
}).then(() => {
api._remove(user).then(res => {
this.$message.success('成功刪除了用戶(hù)' + user.username + '!');
this.getUsers();
console.log(user.id);
}).catch((res) => {
this.$message.error('刪除失敗!');
});
}).catch(() => {
this.$message.info('已取消操作!');
});
},
//刪除多個(gè)用戶(hù)
removeUsers() {
this.$confirm('此操作將永久刪除 ' + this.selected.length + ' 個(gè)用戶(hù), 是否繼續(xù)?', '提示', {
type: 'warning'
}).then(() => {
api._removes().then(res =>{
this.$message.success('刪除了' + this.selected.length + '個(gè)用戶(hù)!');
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}
h1{text-align: center;}
</style>
抽離的api以及代碼的二次封裝:
import axios from 'axios'
import qs from 'qs'
//延時(shí)設(shè)置
axios.defaults.timeout = 5000
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.params = {}
// POST傳參序列化
axios.interceptors.request.use((config) => {
// if (config.method === 'post') {
// config.data = qs.stringify(config.data)
// }
let URL = config.url.split(config.baseURL)
return config
}, (error) => {
return Promise.reject(error)
})
// 返回狀態(tài)判斷
axios.interceptors.response.use((res) => {
//console.log(res)
return res
}, (error) => {
return Promise.reject(error)
})
/**
*
* 備注:也可以使用fetch
*
*/
//封裝獲取數(shù)據(jù)
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)
})
})
};
//封裝發(fā)送數(shù)據(jù)
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)
})
})
}
//封裝更新數(shù)據(jù)
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)
})
})
}
//封裝刪除數(shù)據(jù)
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)
})
})
}
export default {
//此處是本地接口嫌佑,你可在本公司局域網(wǎng)內(nèi)使用
//獲取用戶(hù)數(shù)據(jù)
_get () {
return oGet('http://192.168.1.190/api/v1/accounts');
},
//新建用戶(hù)
_post (params) {
return oPost('http://192.168.1.190/api/v1/accounts',params);
},
//更新用戶(hù)數(shù)據(jù)
_update (param,params) {
return oUpdate('http://192.168.1.190/api/v1/accounts'+'?ids='+param, params);
},
//刪除單個(gè)用戶(hù)
_remove(user){
var userid = user.id;
return oRemove('http://192.168.1.190/api/v1/accounts/'+ userid);
},
//批量刪除
_removes(){
var ids = [];
$.each(this.selected, (i, user) => {
ids.push(user.id);
});
ids = ids.join(",");
return oRemove('http://192.168.1.190/api/v1/accounts/'+ids);
},
}
截圖效果:
1.png
2.png
3.png
4.png
5.png
如果有幫助,請(qǐng)不要吝嗇侨歉,給個(gè)‘star’屋摇,就是對(duì)我的鼓勵(lì)!
https://github.com/sky-xsk/axios-elementui-