zoukankan      html  css  js  c++  java
  • iview Table行编辑、单元格编辑(转载)

    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 () {
                this.getData();
            }
        }
    </script>
    

    分别启动前后端,用浏览器打开URL:http://localhost:8080/#/table1,页面渲染如下

    点击某一行用户名后面的修改按钮,用户名原有数据会成input框,让用户输入修改数据

    当用户修改完成,点击保存,则会把修改后的用户名发送到后端接口,保存到数据库中

    再次刷新浏览器,会看到用户名已经修改了

    3.可编辑行

    src/views/table2.vue文件内容

    <template>
        <div style="padding:32px 64px">
            <h1>可编辑行</h1>
            <Table :data="data" :columns="column" border></Table>
            <div style="text-align:center;margin:16px 0">
                <Page
                    :total="total"
                    :current.sync="current"
                    :page-size-opts="page_size_array"
                    show-sizer
                    show-total
                    @on-change="getData"
                    @on-page-size-change="handleChangeSize"></Page>
            </div>
        </div>
    </template>
    
    <script>
        import axios from 'axios'
    
        export default {
            data() {
                return {
                    editIndex: -1,
                    editName: '',
                    editEmail: '',
                    editStatus: '',
                    statusArray: [
                        {
                            key: '1',
                            value: '1'
                        },
                        {
                            key: '2',
                            value: '2'
                        },
                        {
                            key: '3',
                            value: '3'
                        },
                    ],
                    column: [
                        {
                            type:"index",
                            100,
                            align:'center',
                            title:'ID',
                            key:'id',
                        },
                        {
                            title: "用户名",
                            key: 'name',
                            render: (h, {row, index}) => {
                                let edit;
                                if (this.editIndex === index) {
                                    this.editName = row.name
                                    edit = [h('Input', {
                                        props: {
                                            value: row.name
                                        },
                                        on: {
                                            input: (val) => {
                                                this.editName = val;
                                            }
                                        }
                                    })]
                                } else {
                                    edit = row.name;
                                }
                                return h('div', [edit]);
                            }
                        },
                        {
                            title: "邮箱",
                            key: 'email',
                            render: (h, {row, index}) => {
                                let edit;
                                if (this.editIndex === index) {
                                    this.editEmail = row.email
                                    edit = [h('Input', {
                                        props: {
                                            value: row.email
                                        },
                                        on: {
                                            input: (val) => {
                                                this.editEmail = val;
                                            }
                                        }
                                    })]
                                } else {
                                    edit = row.email;
                                }
                                return h('div', [edit]);
                            }
                        },
                        {
                            title: "等级",
                            key: 'status',
                            render: (h, {row, index}) => {
                                let edit;
                                if (this.editIndex === index) {
                                    this.editStatus = row.status
                                    let options = this.statusArray.map(v => {
                                        return h('Option',{
                                            props: {
                                                value: v.value
                                            }
                                        }, v.key)
                                    })
                                    edit = [h('Select', {
                                        props: {
                                            value: row.status
                                        },
                                        on: {
                                            input: (val) => {
                                                this.editStatus = val;
                                            }
                                        }
                                    },options)]
                                } else {
                                    edit = row.status;
                                }
                                return h('div', [edit]);
                            }
                        },
                        {
                            title: "操作",
                            render: (h, {row, index}) => {
                                if (this.editIndex === index) {
                                    return [
                                        h('Button', {
                                            props: {
                                                type: 'success'
                                            },
                                            on: {
                                                click: () => {
                                                    this.data[index].name = this.editName;
                                                    this.data[index].email = this.editEmail;
                                                    this.data[index].status = this.editStatus;
                                                    this.editIndex = -1;
                                                    axios.post(`http://127.0.0.1:8000/update_user/`,{
                                                        user_id: row.id,
                                                        name: this.editName,
                                                        email: this.editEmail,
                                                        status: this.editStatus
                                                    }).then(res => {
                                                        if(res.data.result) {
                                                            this.$Message.success('修改用户名成功');
                                                        } else {
                                                            this.$Message.error('请求失败');
                                                        }
                                                    })
                                                }
                                            }
                                        }, '保存'),
                                        h('Button', {
                                            props: {
                                                type: 'error'
                                            },
                                            style: {
                                                marginLeft: '6px'
                                            },
                                            on: {
                                                click: () => {
                                                    this.editIndex = -1;
                                                }
                                            }
                                        }, '取消')
                                    ]
                                } else {
                                    return h('Button', {
                                        on: {
                                            click: () => {
                                                this.editName = row.name;
                                                this.editEmail = row.email;
                                                this.editStatus = row.status;
                                                this.editIndex = index;
                                            }
                                        }
                                    }, '修改')
                                }
                            }
                        }
                    ],
                    data: [],
                    loading:false,
                    page_size_array: [10, 20, 30, 40, 60, 100],     // 设置每页可以切换的条数
                    total:0,
                    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 () {
                this.getData();
            }
        }
    </script>
    

    用浏览器打开URL:http://localhost:8080/#/table2,页面渲染如下

    点击某一行操作栏中的修改按钮,用户名和邮箱原有数据会成input框,input框中数据为原数据,等级原有数据处会变成select下拉框让用户选择

    当用户修改完成,点击保存,则会把修改后的用户信息通过POST请求发送到后端接口,保存到数据库中

    再次刷新浏览器,会看到用户名已经修改了

  • 相关阅读:
    ajax如何调用本页数据源不用一般处理程序
    管理员IP匹配方法
    Silverlight DataGrid赋数据源自动生成列表
    Winform WebBrowser加上进度条
    asp.net的几个帮助类
    asp.net App.config配置文件帮助类
    查找集合中某个元素的位置和某个元素的集合
    sqlServer通用分页
    定时执行某个方法
    关于IE6.7.8.FF兼容的问题
  • 原文地址:https://www.cnblogs.com/hao-1234-1234/p/14250065.html
Copyright © 2011-2022 走看看