vue.js+Element實(shí)現(xiàn)表格里的增刪改查
新項(xiàng)目使用的是vue.js 后來(lái)發(fā)現(xiàn)餓了嗎前端編寫的一套框架Element (http://element.eleme.io/#/zh-CN)來(lái)配合vue.js進(jìn)行樣式填充
之前用過(guò)angularjs 用到后來(lái) 發(fā)現(xiàn)越來(lái)越難學(xué) 于是就決定用vue.js
下面就介紹一下vue.js應(yīng)用在表格里的增刪改查
首先引入一下element的js
<script src="plugins/element-ui/index.js"></script>
然后引入需要用到的vue相關(guān)的js文件
<script src="plugins/vue/vue.js"></script> <script src="plugins/vue/vue-resource.js"></script> <script src="plugins/vue/vue-moment.min.js"></script> <script src="js/jquery.min.js"></script>
下面先說(shuō)一下html文件
<div id="user">
<!-- 操作 -->
<ul class="btn-edit fr">
<li >
<el-button type="primary" @click="dialogCreateVisible = true">添加用戶</el-button>
<el-button type="primary" icon="delete" :disabled="selected.length==0" @click="removeUsers()" >刪除</el-button>
<el-button type="primary" icon="edit" :disabled="selected.length==0" >停用</el-button>
<el-button type="primary" icon="edit" :disabled="selected.length==0" >激活</el-button>
</li>
</ul>
<!-- 用戶列表-->
<el-table :data="users"
stripe
v-loading="loading"
element-loading-text="拼命加載中..."
style="width: 100%"
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="120">
</el-table-column>
<el-table-column prop="name"
label="姓名"
width="120">
</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" inline-template
label="注冊(cè)日期"
width="260">
<div>{{ row.create_time | moment('YYYY年MM月DD日 HH:mm:ss')}}</div>
</el-table-column>
<el-table-column inline-template
label="操作"
width="250">
<el-button type="primary" size="mini" @click="removeUser(row)">刪除</el-button>
<el-button type="primary" size="mini" @click="setCurrent(row)">編輯</el-button>
</el-table-column>
</el-table>
<!--分頁(yè)begin-->
<el-pagination class="tc mg"
:current-page="filter.page"
:page-sizes="[10, 20, 50, 100]"
:page-size="filter.per_page"
layout="total, sizes, prev, pager, next, jumper"
:total="total_rows"
@size-change="pageSizeChange"
@current-change="pageCurrentChange">
</el-pagination>
<!--分頁(yè)end-->
</div>
這一段是element的表單以及編輯還有分頁(yè)樣式 可以直接復(fù)制進(jìn)來(lái) 其中添加了一些click操作 后面需要用到,然后我們就開始引入js
了解過(guò)vuejs的應(yīng)該知道這樣的結(jié)構(gòu) data里面填寫我們獲取的數(shù)據(jù) 一些規(guī)則 定義一些變量
在methods進(jìn)行我們的操作
vm = new Vue({
el: '#user',
data:{},
methods:{}
})
首先 我們先從讀取數(shù)據(jù)開始
放入你的url
users是表格綁定的數(shù)組 也是存放從后臺(tái)獲取的數(shù)據(jù)
將需要顯示的數(shù)據(jù)放在filter中
vm = new Vue({
el: '#user',
// 數(shù)據(jù)模型
data: function() {
return {
url: 'url',
users: [],
filter: {
per_page: 10, // 頁(yè)大小
page: 1, // 當(dāng)前頁(yè)
name:'',
username:'',
phone:'',
is_active:'',
sorts:''
},
total_rows: 0,
loading: true,
};
},
methods:{}
})
接下來(lái)我們添加methods
pageSizeChange() 以及 pageCurrentChange()是用于分頁(yè)的函數(shù)
在query() 是用于搜索的項(xiàng)目
getUsers() 就是用于獲取數(shù)據(jù)
methods: {
pageSizeChange(val) {
this.filter.per_page = val;
this.getUsers();
},
pageCurrentChange(val) {
this.filter.page = val;
this.getUsers();
},
query(){
this.filter.name='';
this.filter.username='';
this.filter.phone='';
this.filter[this.select]=this.keywords;
this.getUsers();
},
// 獲取用戶列表
getUsers() {
this.loading = true;
var resource = this.$resource(this.url);
resource.query(this.filter)
.then((response) => {
this.users = response.data.datas;
this.total_rows = response.data.total_rows;
this.loading = false;
})
.catch((response)=> {
this.$message.error('錯(cuò)了哦,這是一條錯(cuò)誤消息');
this.loading = false;
});
},
}
讀取完數(shù)據(jù)之后 我們可以看見數(shù)據(jù)是按照每頁(yè)十條顯示 是上面我們默認(rèn)設(shè)置的
下面進(jìn)行刪除操作 刪除我設(shè)置的是單挑刪除以及多條刪除
因?yàn)閯h除需要選中 所以我們需要加入選中的變量
vm = new Vue({
el: '#user',
// 數(shù)據(jù)模型
data: function() {
return {
url: 'http://172.10.0.201/api/v1/accounts',
users: [
],
filter: {
per_page: 10, // 頁(yè)大小
page: 1, // 當(dāng)前頁(yè)
name:'',
username:'',
phone:'',
is_active:'',
sorts:''
},
total_rows: 0,
loading: true,
selected: [], //已選擇項(xiàng)
};
},
然后在methods也要加入選中的函數(shù)
tableSelectionChange(val) {
console.log(val);
this.selected = val;
},
// 刪除單個(gè)用戶
removeUser(user) {
this.$confirm('此操作將永久刪除用戶 ' + user.username + ', 是否繼續(xù)?', '提示', { type: 'warning' })
.then(() => { // 向請(qǐng)求服務(wù)端刪除
var resource = this.$resource(this.url + "{/id}");
resource.delete({ id: user.id })
.then((response) => {
this.$message.success('成功刪除了用戶' + user.username + '!'); this.getUsers(); })
.catch((response) => {
this.$message.error('刪除失敗!');
});
}) .catch(() => {
this.$message.info('已取消操作!');
});
},
//刪除多個(gè)用戶
removeUsers() {
this.$confirm('此操作將永久刪除 ' + this.selected.length + ' 個(gè)用戶, 是否繼續(xù)?', '提示', { type: 'warning' })
.then(() => {
console.log(this.selected);
var ids = []; //提取選中項(xiàng)的id
$.each(this.selected,(i, user)=> { ids.push(user.id); }); // 向請(qǐng)求服務(wù)端刪除var resource = this.$resource(this.url);
resource.remove({ids: ids.join(",")
}) .then((response) => {
.catch((response) => {
this.$message.error('刪除失敗!');
});
})
.catch(() => {
});
}
接下來(lái)就進(jìn)行到編輯和添加
由于刪除和編輯需要加入表單
<!-- 創(chuàng)建用戶 begin--> <el-dialog title="創(chuàng)建用戶" 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="確認(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> <!-- 修改用戶 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>
因?yàn)橛斜韱?所以我們需要加入表單驗(yàn)證
以及添加和編輯彈出的狀態(tài)
vm = new Vue({
el: '#user',
// 數(shù)據(jù)模型
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 {
url: 'http://172.10.0.201/api/v1/accounts',
users: [
],
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)輸入用戶名', trigger: 'blur' },
{ min: 3, max: 25, message: '長(zhǎng)度在 3 到 25 個(gè)字符'},
{ pattern:/^[A-Za-z0-9]+$/, message: '用戶名只能為字母和數(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)碼'}
]
},
filter: {
per_page: 10, // 頁(yè)大小
page: 1, // 當(dāng)前頁(yè)
name:'',
username:'',
phone:'',
is_active:'',
sorts:''
},
total_rows: 0,
loading: true,
selected: [], //已選擇項(xiàng)
dialogCreateVisible: false, //創(chuàng)建對(duì)話框的顯示狀態(tài)
dialogUpdateVisible: false, //編輯對(duì)話框的顯示狀態(tài)
createLoading: false,
updateLoading: false,
};
},
下面就加入添加和編輯的函數(shù)
methods: {
tableSelectionChange(val) {
console.log(val);
this.selected = val;
},
pageSizeChange(val) {
console.log(`每頁(yè) ${val} 條`);
this.filter.per_page = val;
this.getUsers();
},
pageCurrentChange(val) {
console.log(`當(dāng)前頁(yè): ${val}`);
this.filter.page = val;
this.getUsers();
},
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;
},
// 重置表單
reset() {
this.$refs.create.resetFields();
},
query(){
this.filter.name='';
this.filter.username='';
this.filter.phone='';
this.filter[this.select]=this.keywords;
this.getUsers();
},
// 獲取用戶列表
getUsers() {
this.loading = true;
var resource = this.$resource(this.url);
resource.query(this.filter)
.then((response) => {
this.users = response.data.datas;
this.total_rows = response.data.total_rows;
this.loading = false;
})
.catch((response)=> {
this.$message.error('錯(cuò)了哦,這是一條錯(cuò)誤消息');
this.loading = false;
});
},
// 創(chuàng)建用戶
createUser() {
// 主動(dòng)校驗(yàn)
this.$refs.create.validate((valid) => {
if (valid) {
this.create.id=getuuid();
this.createLoading=true;
var resource = this.$resource(this.url);
resource.save(this.create)
.then((response) => {
this.$message.success('創(chuàng)建用戶成功!');
this.dialogCreateVisible=false;
this.createLoading=false;
this.reset();
this.getUsers();
})
.catch((response) => {
var data=response.data;
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;
}
});
},
// 更新用戶資料
updateUser() {
this.$refs.update.validate((valid) => {
if (valid) {
this.updateLoading=true;
var actions = {
update: {method: 'patch'}
}
var resource = this.$resource(this.url,{},actions);
resource.update({"ids":this.currentId},this.update)
.then((response) => {
this.$message.success('修改用戶資料成功!');
this.dialogUpdateVisible=false;
this.updateLoading=false;
//this.reset();
this.getUsers();
})
.catch((response) => {
var data=response.data;
console.log(data);
if(data instanceof Array){
this.$message.error(data[0]["message"]);
}
else if(data instanceof Object){
this.$message.error(data["message"]);
}
this.updateLoading=false;
});
}
else {
//this.$message.error('存在輸入校驗(yàn)錯(cuò)誤!');
return false;
}
});
},
// 刪除單個(gè)用戶
removeUser(user) {
this.$confirm('此操作將永久刪除用戶 ' + user.username + ', 是否繼續(xù)?', '提示', { type: 'warning' })
.then(() => {
// 向請(qǐng)求服務(wù)端刪除
var resource = this.$resource(this.url + "{/id}");
resource.delete({ id: user.id })
.then((response) => {
this.$message.success('成功刪除了用戶' + user.username + '!');
this.getUsers();
})
.catch((response) => {
this.$message.error('刪除失敗!');
});
})
.catch(() => {
this.$message.info('已取消操作!');
});
},
//刪除多個(gè)用戶
removeUsers() {
this.$confirm('此操作將永久刪除 ' + this.selected.length + ' 個(gè)用戶, 是否繼續(xù)?', '提示', { type: 'warning' })
.then(() => {
console.log(this.selected);
var ids = [];
//提取選中項(xiàng)的id
$.each(this.selected,(i, user)=> {
ids.push(user.id);
});
// 向請(qǐng)求服務(wù)端刪除
var resource = this.$resource(this.url);
resource.remove({ids: ids.join(",") })
.then((response) => {
this.$message.success('刪除了' + this.selected.length + '個(gè)用戶!');
this.getUsers();
})
.catch((response) => {
this.$message.error('刪除失敗!');
});
})
.catch(() => {
this.$Message('已取消操作!');
});
}
}
這就是整個(gè)增刪改查的過(guò)程
demo地址:http://xiazai.jb51.net/201701/yuanma/vuejs-element_jb51.rar
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
VUE屏幕整體滾動(dòng)(滑動(dòng)或滾輪)原生方法舉例
為了實(shí)現(xiàn)全屏滾動(dòng)效果,我們首先需要使用Vue.js框架搭建項(xiàng)目,這篇文章主要給大家介紹了關(guān)于VUE屏幕整體滾動(dòng)(滑動(dòng)或滾輪)原生方法的相關(guān)資料,需要的朋友可以參考下2024-01-01
vue router返回到指定的路由的場(chǎng)景分析
這篇文章主要介紹了vue router返回到指定的路由的場(chǎng)景分析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11
vue使用element-resize-detector監(jiān)聽元素寬度變化方式
這篇文章主要介紹了vue使用element-resize-detector監(jiān)聽元素寬度變化方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
詳解實(shí)現(xiàn)vue的數(shù)據(jù)響應(yīng)式原理
這篇文章主要介紹了詳解實(shí)現(xiàn)vue的數(shù)據(jù)響應(yīng)式原理,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
基于el-table實(shí)現(xiàn)行內(nèi)增刪改功能
這篇文章主要介紹了基于el-table實(shí)現(xiàn)行內(nèi)增刪改功能,用過(guò)通過(guò)操作按鈕點(diǎn)擊刪除或者編輯功能即可實(shí)現(xiàn)相應(yīng)的效果,下面小編給大家分享實(shí)例代碼感興趣的朋友跟隨小編一起看看吧2024-04-04
vue3 element-plus如何使用icon圖標(biāo)組件
這篇文章主要介紹了vue3 element-plus如何使用icon圖標(biāo)組件問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
淺談Vue使用Elementui修改默認(rèn)的最快方法
這篇文章主要介紹了淺談Vue使用Elementui修改默認(rèn)的最快方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12
在Vue3.x中實(shí)現(xiàn)類似React.lazy效果的方法詳解
React 的 React.lazy 功能為組件懶加載提供了原生支持,允許開發(fā)者將組件渲染推遲到實(shí)際需要時(shí)再進(jìn)行,雖然 Vue3.x 沒(méi)有一個(gè)直接對(duì)應(yīng)的 lazy 函數(shù),但我們可以通過(guò)動(dòng)態(tài)導(dǎo)入和 defineAsyncComponent 方法來(lái)實(shí)現(xiàn)類似的效果,需要的朋友可以參考下2024-03-03

