iView学习笔记(二):Table行编辑操作
转载来源:https://www.cnblogs.com/renpingsheng/p/11256238.html
1.前端准备工作
首先新建一个项目,然后引入iView插件,配置好router
npm安装iView
npm install iview --save
cnpm install iview --save
src/main.js
文件内容
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import iView from 'iview';
import 'iview/dist/styles/iview.css';
Vue.use(iView);
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
src/router.js
文件内容
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/table1',
component: () => import('./views/table1.vue')
},
{
path: '/table2',
component: () => import('./views/table2.vue')
},
{
path:'/',
redirect:'/table1'
}
]
})
2.后端准备工作
环境说明
python版本:3.6.6
Django版本:1.11.8
数据库:MariaDB 5.5.60
新建Django项目,在项目中新建app,配置好数据库api_test/app01/models.py
文件内容
from django.db import models
class UserProfile(models.Model):
name = models.CharField("用户名", max_length=32)
email = models.EmailField(max_length=32)
status = models.IntegerField(default=1)
def to_dic(self):
return dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]])
api_test/urls.py
文件内容
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^update_user/$',views.update_user),
url(r'^get_user/$',views.get_user_list),
]
api_test/app01/views.py
文件内容
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import UserProfile
@csrf_exempt
def update_user(request):
request_dict = json.loads(request.body)
user_id = request_dict.get("user_id")
name = request_dict.get("name")
email = request_dict.get("email")
status = request_dict.get("status")
try:
UserProfile.objects.filter(id=int(user_id)).update(name=name, email=email, status=status)
return JsonResponse({"result": True})
except Exception as e:
return JsonResponse({"result": False})
def get_user_list(request):
# for i in range(1, 1001): // 向数据库创建1000条记录
# name = "user" + str(i)
# email = "user%s@qq.com" % str(i)
# status = random.randint(1, 3)
# user_obj = UserProfile(name=name, email=email, status=status)
# user_obj.save()
current = request.GET.get("current", 1)
size = request.GET.get("size", 0)
sortType = request.GET.get("sortType")
filterType = request.GET.get("filterType")
res_list = []
try:
user_list = UserProfile.objects.all()
if filterType and filterType != "undefined":
user_list = user_list.filter(status=int(filterType))
total = user_list.count()
if current and size:
end = int(current) * int(size)
start = (int(current) - 1) * int(size)
user_list = user_list[start:end]
except Exception as e:
print(e)
return JsonResponse({"result": False}, safe=False)
for user in user_list:
res_list.append(user.to_dic())
if sortType == "desc":
res_list = sorted(res_list, key=lambda x: x["id"], reverse=True)
else:
res_list = sorted(res_list, key=lambda x: x["id"], reverse=False)
res = {
"data": {
"list": res_list,
"total": total
},
"result": True
}
return JsonResponse(res, safe=False)
这里前端向后端发送POST请求时,后端没有执行csrftoken验证,前端获取csrftoken,后端进行csrftoken验证不在本文示例之内
3.可编辑单元格
src/views/table1.vue
文件内容
<template>
<div style="padding:32px 64px">
<h1>可编辑单元格</h1>
<Table
:columns="columns"
:data="data"
:loading="loading"
border
size="small">
</Table>
<div style="text-align:center;margin:16px 0">
<Page
:total="total"
:current.sync="current"
show-total
@on-change="getData"></Page>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
columns:[
{
type:"index",
100,
align:'center',
title:'ID',
key:'id',
},
{
title:'用户名',
key:'name',
render: (h, {row, index}) => {
let edit;
let control;
if (this.editIndex === index) {
edit = [h('Input', {
props: {
value: row.name
},
on: {
input: (val) => {
this.editValue = val;
}
}
})];
control = [
h('Icon', {
style: {
cursor: 'pointer',
margin: '8px'
},
props: {
type: 'md-checkmark',
size: 16,
color: '#19be6b'
},
on: {
click: () => {
this.data[index].name = this.editValue;
this.editIndex = -1;
axios.post(`http://127.0.0.1:8000/update_user/`,{
user_id: row.id,
name: this.editValue,
email: row.email,
status: row.status
}).then(res => {
if(res.data.result) {
this.$Message.success('修改用户名成功');
} else {
this.$Message.error('请求失败');
}
})
}
}
}),
h('Icon', {
style: {
cursor: 'pointer',
margin: '8px'
},
props: {
type: 'md-close',
size: 16,
color: '#ed4014'
},
on: {
click: () => {
this.editIndex = -1;
}
}
})
]
} else {
edit = row.name;
control = [h('Icon', {
style: {
cursor: 'pointer'
},
props: {
type: 'ios-create-outline',
size: 16
},
on: {
click: () => {
this.editIndex = index;
this.editValue = row.name;
}
}
})]
}
return h('Row', [
h('Col', {
props: {
span: 16
}
}, edit),
h('Col', {
props: {
span: 6
}
}, control)
])
}
},
{
title:'状态',
key:'status',
render: (h, {row}) => {
if (row.status === 1) {
return h('Tag', {
props: {
color: 'green'
}
}, "等级 1")
} else if (row.status === 2) {
return h('Tag', {
props: {
color: 'red'
}
}, "等级 2")
} else if (row.status === 3) {
return h('Tag', {
props: {
color: 'blue'
}
}, "等级 3")
}
},
},
{
title:'邮箱',
key:'email',
}
],
data:[],
loading:false,
total:0,
editIndex: -1,
editValue: '',
current:1, // 当前页面
size:10, // 设置初始每页可以显示的数据条数
}
},
methods:{
getData (){
if (this.loading) return;
this.loading = true;
axios.get(`http://127.0.0.1:8000/get_user/?current=${this.current}&size=${this.size}`).then(res => {
if(res.data.result) {
this.data = res.data.data.list;
this.total = res.data.data.total;
this.loading = false
} else {
this.$Message.error('请求失败');
}
})
},
handleChangeSize (val){
this.size = val;
this.$nextTick(() => {
this.getData();
})
}
},
mounted () {