server端数据回调渲染list以及分页 antd+vue +djangorestframework 完结撒花

<template>
<div>
  <div id="components-form-demo-advanced-search">
    <a-form class="ant-advanced-search-form" :form="form"  :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }"   @submit="handleSearch" :headers="headers">
      <a-row :gutter="24">
        <a-col
          v-for="v,i in headers"
          :key="i"
          :span="8"
          :style="{ display: i < count ? 'block' : 'none' }"
        >
          <a-form-item :label="`${v}`" >
            <a-input
              v-decorator="[
                `${v}`,
                {
                  rules: [
                    {
                      required: false,
                      message: 'Input something!',
                    },
                  ],
                  initialValue: ''
                },
              ]"
              placeholder="placeholder"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" :style="{ textAlign: 'right' }">
          <a-button type="primary" html-type="submit">
            查询
          </a-button>
          <a-button :style="{ marginLeft: '8px' }" @click="handleReset">
            清除
          </a-button>
          <a :style="{ marginLeft: '8px', fontSize: '12px' }" @click="toggle">
            收起 <a-icon :type="expand ? 'up' : 'down'" />
          </a>
        </a-col>
      </a-row>
    </a-form>

  </div>
  <div><modalbox></modalbox></div>

  <div>
    <a-table :columns="columns" :data-source="data" :scroll="{ x: 1300,y:1500}" class="tb_list" ref="table"
    :pagination="pagination"
    :row-selection="rowSelection"
    :rowKey="record=>record.id"
    :loading="loading"
    @change="handleTableChange"
  >


  
  <span slot="action" slot-scope="text, record" class="sup">
      <a-button type="link" @click="showModal(record)" style="color:green">Edit</a-button>
      <a-popconfirm
      placement="bottomRight"
      title="Are you sure delete it?"
      ok-text="Yes"
      cancel-text="No"
      @confirm="confirm"
      @cancel="cancel"
      >
      <a href="#" style="color:red">Delete</a>
      </a-popconfirm> 

  </span>
  </a-table>
  <div>
    <a-modal v-model="visible" title="Basic Modal" @ok="handleOk" class="edit-mask">
       <a-form name="edit_form" :form="formedit" id="editform">
        <a-form-model-item label="name" id="name-item">
          <a-input placeholder="input placeholder" 
          v-decorator="[
          'name',
          { rules: [{ required: true, message: 'Please input your name!' }],initvalue:{} },
        ]"
          />
        </a-form-model-item>
        <a-form-model-item label="age" id="age-item">
          <a-input  placeholder="input placeholder" 
          v-decorator="[
          'age',
          { rules: [{ required: true, message: 'Please input your age!' }],initvalue:{} },

        ]"
          />
        </a-form-model-item>
        <a-form-model-item label="address" id="address-item">
          <a-input  placeholder="input placeholder" 
          v-decorator="[
          'address',
          { rules: [{ required: true, message: 'Please input your address!' }],initvalue:{} },
        ]"
          />
        </a-form-model-item>
       </a-form>
    </a-modal>
  </div>
  </div>


</div>




</template>
      

<script>

import _ from 'lodash';
import FormSearch from '@/components/FormSearch.vue'
import modalbox from '@/components/AddModal.vue'
const columns = [
  { title: 'id', dataIndex: 'id', key: 'id', width: 150},
  { title: 'address', dataIndex: 'address', key: 'address' ,width: 150},
  { title: 'age', dataIndex: 'age', key: 'age',width: 150 },
  { title: 'name', dataIndex: 'name', key: 'name',width: 150 , 

  },
  {title: 'operate',key: 'operation',fixed: 'right', width:'auto',scopedSlots: { customRender: 'action' },
  },
];


const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  onSelect: (record, selected, selectedRows) => {
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows);
  },
};

export default {
  name:'tablelist',
  computed: {
    count() {
      return this.expand ? 4 : 3;
    },
  },
  data() {
    return {
      loading: false,
      formedit: this.$form.createForm(this, { name: 'edit_form' }),
      form: this.$form.createForm(this, { name: 'advanced_search' }),
      expand: false,
      headers:["versionNo","name","age"],
      visible:false,
      data:[],
      queryInfo:{
        page_size:10,
        page:1

      },
      columns,
      rowSelection,
      pagination:{
                defaultPageSize:10,
                defaultCurrent:1,
                total:20,
                showTotal: total => `共 ${total} 条数据`,
       
                showSizeChanger:true,

                pageSizeOptions: [ '10', '20', '30','50'],

                onShowSizeChange:(current, pageSize)=>this.pageSize = pageSize

                }


    };
  },

  created () {
    this.getUserList()

    },

  methods: {

    // getUserList when enter table Page

    getUserList(){
      this.$axios({
        url:  '/demo-service/api/v1/vue/',
        method: 'get',
        params: this.queryInfo
      
      }).then(res => {
        const pagination = { ...this.pagination };
        // Read total count from server
        // pagination.total = data.totalCount;
        pagination.total =res.data.data.totals ;
        this.loading = false;
        this.data = res.data.data.data;
        this.pagination = pagination;
      });

    },
    // 
    handleTableChange(pagination, filters, sorter) {
      console.log(pagination);
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      this.pagination = pager;
      this.fetch({
        pageSize: pagination.pageSize,
        page: pagination.current,

      });
    },
    fetch(params = {}) {
      console.log('params:', params);
      this.loading = true;
      this.$axios({
        url:'/demo-service/api/v1/vue/',
        method: 'get',
        params: {...params},
   
      }).then(res => {
        const pagination = { ...this.pagination };
        // Read total count from server
        // pagination.total = data.totalCount;
        pagination.total =res.data.data.totals ;
        this.loading = false;
        this.data = res.data.data.data;
        this.pagination = pagination;
      });
    },
  

  
    // query table 
    handleSearch(e) {
      e.preventDefault();
      this.form.validateFields((error, values) => {
        this.loading = true;
        this.$axios(
        {
                    url: '/demo-service/api/v1/vue/',
                    method: 'get',
                    params: 
                      values
                  ,
                }
      ) .then( (response)=> {
            console.log(response.data.data);
            this.data=response.data.data.data
            this.pagination.total=response.data.data.totals

            
          }
          

      ).catch(function (error) {
              console.log(error);});
        
       
        
      });
    },
    // reset form search 
    handleReset() {
      this.form.resetFields();
    },
    // expand control 
    toggle() {
      this.expand = !this.expand;
    },

    // excute axios delete call 
    confirm(e) {
      this.$message.success('Click on Yes');
    },
    //do nothing 
    cancel(e) {
      this.$message.error('Click on No');
    },

    showModal(record) {
      this.visible = true;
     
        // console.log(record.id+"  "+record.name+" ",record.age+""+record.address+"xxxxxxxxxxxxxxx");
        // console.log(this.$route);
        // 读取list接口数据赋值给编辑页面
        this.$nextTick(()=>{
        this.formedit.setFieldsValue({name:record.name,age:record.age,address:record.address})
                           });

    },
    handleOk(e) {
      // 读取修改后表单
      this.$nextTick(()=>{
      let v=  this.formedit.getFieldsValue()
      console.log("获取修改后数据:\n")
      console.log(v);
                           });
      
      this.visible = false;
    },
  
  },
  components:{'formsearch':FormSearch,modalbox},

};
</script>
<style lang="less" scoped>
.sup{
  margin-left: -13px;
  
}

</style>

  

服务端自定义分页器:

from rest_framework.response import Response


class ListPagination(pagination.PageNumberPagination):
    """"user custom pagination class"""
    page_size_query_param = "page_size"
    page_query_param = 'page'
    page_size = 10
    max_page_size = 100

    def get_paginated_response(self, data):
        """
        重写分页response方法,参考原PageNumberPagination class
        """
        return Response({
            'next': self.get_next_link(),
            'previous': self.get_previous_link(),
            'data': data,
            'page_size': self.page.paginator.per_page,
            'page': self.page.start_index() // self.page.paginator.per_page + 1,
            'totals': self.page.paginator.count,
        })

  

服务端数据返回结构:

 

{
  "data": {
    "next": null,
    "previous": null,
    "data": [
      {
        "id": 1,
        "name": "张三",
        "age": 11,
        "address": "深圳"
      },
      {
        "id": 2,
        "name": "tomas",
        "age": 10,
        "address": "深圳111"
      },
      {
        "id": 3,
        "name": "tomas22",
        "age": 10,
        "address": "深圳22"
      },
      {
        "id": 4,
        "name": "adny",
        "age": 33,
        "address": "深圳33"
      },
      {
        "id": 5,
        "name": "ailsi",
        "age": 33,
        "address": "深圳33"
      },
      {
        "id": 6,
        "name": "lisa",
        "age": 33,
        "address": "深圳33"
      },
      {
        "id": 7,
        "name": "xuyan",
        "age": 33,
        "address": "深圳33"
      },
      {
        "id": 8,
        "name": "yukio",
        "age": 33,
        "address": "深圳33"
      },
      {
        "id": 9,
        "name": "toby",
        "age": 33,
        "address": "深圳33"
      },
      {
        "id": 10,
        "name": "陈权",
        "age": 33,
        "address": "前海信利康大厦111222222222222222222223"
      },
      {
        "id": 11,
        "name": "陈权3",
        "age": 33,
        "address": "前海信利康大厦111222222222222222222223"
      },
      {
        "id": 12,
        "name": "陈权4",
        "age": 33,
        "address": "前海信利康大厦111222222222222222222223"
      },
      {
        "id": 13,
        "name": "siba1",
        "age": 33,
        "address": "前海信利康大厦111222222222222222222223"
      },
      {
        "id": 14,
        "name": "sibuuu1",
        "age": 33,
        "address": "前海信利康大厦111222222222222222222223"
      }
    ],
    "page_size": 20,
    "page": 1,
    "totals": 14
  },
  "msg": "ok",
  "code": 200,
  "success": true
}

  

posted @ 2021-05-01 04:02  不带R的墨菲特  阅读(126)  评论(0编辑  收藏  举报