iView study notes (c): table search, filter and hide columns operation

iView study notes (c): table search, filter and hide a column operations

1. The rear end of the preparatory work

Environment Description

python版本:3.6.6
Django版本:1.11.8
数据库:MariaDB 5.5.60

New Django project, the new app in the project, configured database

api_test/app01/models.pydocument content

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.pydocument content

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.pydocument content

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.pydocument content

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)

When this front end to the rear end of the POST request sent, is not performed csrftoken backend authentication, obtaining csrftoken front end, a rear end for example of the verification is not csrftoken herein

2. The front end of the preparatory work

First create a new project, then the introduction of iView plug-configured router

npm install iView

npm install iview --save
cnpm install iview --save

src/main.jsdocument content

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.jsdocument content

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.vuedocument content

<template>
    <div style="padding:32px 64px">
        <h1>在外部进行表格的搜索,过滤,隐藏某列的操作</h1>
        <br><br>
        <Form inline :label-width="80">
            <FormItem label="主机名称:">
                <Input v-model="form.searchoHostname" placeholder="请输入" style="width:200px;"/>
            </FormItem>
            <FormItem label="使用状态:">
                <Select v-model="form.searchHostStatus" placeholder="请选择" style="width: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>

Browser to open the URL of: http://localhost:8080/#/table1, page rendering as follows

Uncheck the IP address column, the following table does not show the IP address column

In the 主机名称search box, enter content

In the search results, cancel the last modification time column display

To 主机状态search

For 主机名称and 主机状态conduct joint search

Guess you like

Origin www.cnblogs.com/renpingsheng/p/11266436.html