iView学习笔记(四):Form表单操作

1.后端准备

环境说明

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

新建Django项目,在项目中新建app,配置好数据库

2.后端代码(基于CBV方式)

api_test/app01/models.py文件内容

from django.db import models

from .utils.parse_time import parse_datetime_to_string

class HostInfo(models.Model):
    hostname = models.CharField("主机名", max_length=32)
    ip = models.CharField("IP地址", max_length=16)
    status = models.CharField("主机状态", max_length=16)
    date = models.DateTimeField("主机添加时间", auto_now_add=True)

    def to_dict(self):
        return {
            "hostname": self.hostname,
            "id": self.pk,
            "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 django.views.decorators.csrf import csrf_exempt

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^host/$', csrf_exempt(views.HostInfoView.as_view())),
]

api_test/app01/views.py文件内容

class HostInfoView(View):
    def get(self, request):
        res_list = []
        host_list = HostInfo.objects.all()
        for i in host_list:
            res_list.append(i.to_dict())
        return JsonResponse({"data": res_list, "result": True}, safe=False)

    def post(self, request):
        data = json.loads(request.body)
        res = {"result": False}
        id = data.get("id")
        hostname = data.get("hostname")
        ip = data.get("ip")
        status = data.get("status")
        operate = data.get("operate")
        if operate == "delete":
            try:
                HostInfo.objects.filter(id=id).delete()
                res = {"result": True}
            except Exception:
                res = {"result": False}
        elif operate == "create":
            try:
                HostInfo.objects.create(hostname=hostname, ip=ip, status=status)
                res = {"result": True}
            except Exception:
                res = {"result": False}
        elif operate == "edit":
            try:
                HostInfo.objects.filter(id=id).update(hostname=hostname, ip=ip, status=status)
                res = {"result": True}
            except Exception:
                res = {"result": False}
        return JsonResponse(res, safe=False)

3.前端代码

首先新建一个项目,然后引入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: '/form1',
            component: () => import('./views/Form1.vue')
        },
        {
            path:'/',
            redirect:'/form1'
        }
    ]
})

src/views/Form1.vue文件内容

<template>
    <div style="padding: 32px 200px;">
        <h1>Form组件实践</h1>
        <br><br>
        <Table border :columns="tableColumns" :data="tableData"></Table>
        <Button @click="handleOpenCreate">添加</Button>
        <Modal :title="type === 'create' ? '新增主机':'修改主机'" v-model="openModal" @on-ok="handleOk" @on-cancel="handleCancel">
            <Form :model="ModelForm" :label-width="70">
                <FormItem label="主机名称">
                    <Input v-model="ModelForm.hostname"/>
                </FormItem>
                <FormItem label="IP地址">
                    <Input v-model="ModelForm.ip"/>
                </FormItem>
                <FormItem label="主机状态">
                    <Select v-model="ModelForm.status">
                        <Option label="processing" value="processing"/>
                        <Option label="error" value="error"/>
                    </Select>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>

<script>
    import axios from 'axios'

    export default {
        data() {
            return {
                tableData: [],
                openModal: false,
                deleteModal: false,
                type: 'create', // create || edit
                editIndex: -1,
                ModelForm: {
                    id: '',
                    hostname: '',
                    ip: '',
                    status: '',
                    operate: ''
                },
                tableColumns: [
                    {
                        title: '主机名称',
                        key: 'hostname'
                    },
                    {
                        title: 'IP地址',
                        key: 'ip'
                    },
                    {
                        title: '主机状态',
                        key: 'status'
                    },
                    {
                        title: '最后修改时间',
                        key: 'when_insert'
                    },
                    {
                        title: '操作',
                        render: (h, params) => {
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                    },
                                    on: {
                                        click: () => {
                                            this.handleOpenEdit(params.row)
                                        }
                                    }
                                }, '修改'),
                                h('Button', {
                                    props: {
                                        type: 'error',
                                    },
                                    style: {
                                        marginLeft: '10px'
                                    },
                                    on: {
                                        click: () => {
                                            // this.$router.push({path: '/hostperforms', query: {host_id: Number(params.row.host_id)}})
                                            this.handleDelete(params.row)
                                        }
                                    }
                                }, '删除'),
                            ]);
                        }
                    }
                ]
            }
        },
        mounted() {
            this.getData()
        },
        methods: {
            handleOpenEdit(row) {
                this.openModal = true;
                this.type = 'edit';
                this.ModelForm = row;
            },
            handleOpenCreate() {
                this.openModal = true;
                this.type = 'create';
            },
            handleCancel() {
                this.openModal = false;
                this.ModelForm = {
                    hostname: '',
                    ip: '',
                    status: '',
                }
            },
            handleOk() {
                this.ModelForm.operate = this.type
                axios.post('http://127.0.0.1:8000/host/',this.ModelForm).then(res => {
                    if (res.data.result) {
                        this.$Message.success('请求成功');
                        this.hostRow.status = this.ModelForm.status
                    } else {
                        this.$Message.error('请求失败');
                    }
                })
                this.openModal = false;
                this.ModelForm = {
                    hostname: '',
                    ip: '',
                    status: '',
                }
                this.getData();
            },
            getData() {
                axios.get('http://127.0.0.1:8000/host/').then(res => {
                    if (res.data.result) {
                        this.tableData = res.data.data;
                    } else {
                        this.$Message.error('请求失败');
                    }
                })
            },
            handleDelete(row) {
                this.$Modal.confirm({
                    title: '警告',
                    content: '正在删除主机信息,是否继续?',
                    onOk: () => {
                        row.operate = "delete"
                        axios.post('http://127.0.0.1:8000/host/', row).then(res => {
                            if (res.data.result) {
                                this.$Message.success('删除主机成功');
                                this.getData();
                            } else {
                                this.$Message.error('删除主机失败');
                            }
                        })
                    },
                    onCancel: () => {
                        this.$Message.info('取消删除');
                    }
                });
            }
        }
    }
</script>

<style scoped>

</style>

分别运行前后端代码,浏览器打开URL:http://127.0.0.1:8080/#/form1,会在页面列出所有主机

点击某台主机主机后的修改按钮,弹出模态框,模态框的title为:修改主机

点击页面的新增按钮,弹出模态框,模态框的title为:新增主机

点击某台主机后的删除按钮,弹出对话框,提示用户正在删除主机

posted @ 2019-07-31 11:45  renpingsheng  阅读(8591)  评论(0编辑  收藏  举报