iView学习笔记(三):表格搜索,过滤及隐藏某列操作
1.后端准备工作
环境说明
python版本:3.6.6
Django版本:1.11.8
数据库:MariaDB 5.5.60
新建Django项目,在项目中新建app,配置好数据库
api_test/app01/models.py
文件内容
from django.db import models
from .utils.parse_time import parse_datetime_to_string
HOST_STATUS = (
(1, "processing"),
(2, "error"),
)
class HostInfo(models.Model):
hostname = models.CharField("主机名", max_length=32)
ip = models.CharField("IP地址", max_length=16)
status = models.IntegerField("主机状态", choices=HOST_STATUS, default=1)
date = models.DateTimeField("主机添加时间", auto_now_add=True)
def to_dict(self):
return {
"hostname": self.hostname,
"ip": self.ip,
"status": self.status,
"when_insert": parse_datetime_to_string(self.date),
}
app01/utils/parse_time.py
文件内容
def parse_datetime_to_string(datetime_str, flag=True):
"""
把datetime时间转化成时间字符串
:param datetime_str: datetime生成的时间,例子:datetime.datetime.now()
或者: datetime.datetime.now() - datetime.timedelta(hours=1) # 一个小时之前
或者: datetime.datetime.now() - datetime.timedelta(days=1) # 一天之前
:return:
"""
# 将日期转化为字符串 datetime => string
# 在数据库中定义字段信息时为:models.DateTimeField(auto_now_add=True)
# 查询数据库之后,使用此方法把查询到的时间转换成可用的时间字符串
# when_insert__range=(an_hour_time, now_time)
# an_hour_time和 now_time 都是 datetime时间字符串,查询两个datetime时间字符串之间的数据
if flag:
return datetime_str.strftime('%Y-%m-%d %H:%M:%S')
else:
return datetime_str.strftime('%Y-%m-%d')
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'^host/$', views.host_list),
]
api_test/app01/views.py
文件内容
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import HostInfo
@csrf_exempt
def host_list(request):
# for i in range(1, 31):
# hostname = random.choice(["beijing-aws-0","shanghai-aliyun-0"]) + str(i)
# ip = "192.168.100.%d" % i
# status = random.randint(1, 2)
# host_obj = HostInfo(hostname=hostname, ip=ip, status=status)
# host_obj.save()
if request.method == "GET":
query = request.GET.get("query_string")
status = request.GET.get("status")
res_list = []
host_list = HostInfo.objects.all()
if query:
host_list = host_list.filter(hostname__icontains=query)
if status:
host_list = host_list.filter(status=status)
for i in host_list:
res_list.append(i.to_dict())
return JsonResponse({"data": res_list, "result": True}, safe=False)
elif request.method == "POST":
data = json.loads(request.body)
try:
HostInfo.objects.create(**data)
res = {"status": "success"}
except Exception:
res = {"status": "fail"}
return JsonResponse(res, safe=False)
这里前端向后端发送POST请求时,后端没有执行csrftoken验证,前端获取csrftoken,后端进行csrftoken验证不在本文示例之内
2.前端准备工作
首先新建一个项目,然后引入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:'/',
redirect:'/table1'
}
]
})
src/views/table1.vue
文件内容
<template>
<div style="padding:32px 64px">
<h1>在外部进行表格的搜索,过滤,隐藏某列的操作</h1>
<br><br>
<Form inline :label-width="80">
<FormItem label="主机名称:">
<Input v-model="form.searchoHostname" placeholder="请输入" style="200px;"/>
</FormItem>
<FormItem label="使用状态:">
<Select v-model="form.searchHostStatus" placeholder="请选择" style="200px">
<Option :value="1">运行中</Option>
<Option :value="2">异常</Option>
</Select>
</FormItem>
<Button type="primary" @click="getData" style="margin-right:8px;">查询</Button>
<Button @click="handleReset">重置</Button>
</Form>
<CheckboxGroup v-model="showColumns">
<Checkbox :label="0">主机名称</Checkbox>
<Checkbox :label="1">IP 地址</Checkbox>
<Checkbox :label="2">使用状态</Checkbox>
<Checkbox :label="3">最后修改时间</Checkbox>
</CheckboxGroup>
<Button type="primary" icon="md-add" @click="createDialog=true" style="margin-top:20px;">新建</Button>
<br>
<br>
<Table :data="tableData" :columns="filterColumns" :loading="loading" size="small"></Table>
<Modal v-model="createDialog" title="新建主机">
<Form>
<FormItem>
<Input v-model="createHostForm.hostname" placeholder="主机名称"/>
</FormItem>
<FormItem>
<Input v-model="createHostForm.ip" placeholder="IP 地址"/>
</FormItem>
<FormItem>
<Select v-model="createHostForm.status" placeholder="使用状态">
<Option :value="1">运行中</Option>
<Option :value="2">异常</Option>
</Select>
</FormItem>
</Form>
<Button slot="footer" type="primary" @click="handleCreate">创建</Button>
</Modal>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
tableData: [],
loading: false,
columns: [
{
title: "主机名称",
key: 'hostname',
},
{
title: "IP地址",
key: 'ip',
},
{
title: "等级",
key: 'status',
render: (h, {row}) => {
if (row.status === 1) {
return h('Badge', {
props: {
status: 'processing',
text: '运行中'
}
})
} else if (row.status === 2) {
return h('Badge', {
props: {
status: 'error',
text: '异常'
}
})
}
}
},
{
title: "最后修改时间",
key: 'when_insert',
}
],
form: {
searchoHostname: '',
searchHostStatus: '',
},
createDialog: false,
createHostForm: {
hostname: '',
ip: '',
status: '',
},
isCreate: false,
showColumns: [0, 1, 2, 3],
}
},
computed: {
filterColumns() {
const columns = [...this.columns];
const filterColumns = [];
this.showColumns.sort().forEach(item => {
filterColumns.push(columns[item])
});
return filterColumns
}
},
methods: {
getData() {
if (this.loading) return;
this.loading = true;
axios.get(`http://127.0.0.1:8000/host/?query_string=${this.form.searchoHostname}&status=${this.form.searchHostStatus}`).then(res => {
console.log(res.data)
if(res.data.result) {
setTimeout(() => {
this.tableData = res.data.data;
this.loading = false;
}, 1000)
} else {
this.$Message.error('请求失败');
}
})
},
handleReset() {
this.form.searchoHostname = "";
this.form.searchHostStatus = "";
this.getData();
},
handleCreate() {
const hostname = this.createHostForm.hostname;
const ip = this.createHostForm.ip;
const status = this.createHostForm.status;
if (hostname === '') {
this.$Message.error("请输入主机名称");
return;
}
if (ip === '') {
this.$Message.error("请输入IP地址");
return;
}
if (status === '') {
this.$Message.error("请选择使用状态");
return;
}
this.isCreate = true;
axios.post('http://127.0.0.1:8000/host/', this.createHostForm).then(res => {
if(res.data.result) {
this.createDialog=false
this.$Message.success('添加主机成功');
} else {
this.$Message.error('添加主机失败');
}
})
}
},
mounted() {
this.getData();
}
}
</script>
浏览器打开URL:http://localhost:8080/#/table1
,页面渲染如下
取消选中IP地址列,则下面的table中不显示IP地址列
在主机名称
框中输入内容进行搜索
在搜索结果中,取消最后修改时间列的显示
对主机状态
进行搜索
对主机名称
和主机状态
进行联合搜索