Vue uses v-model to encapsulate the entire process of el-pagination components

Vue uses v-model to encapsulate the entire process of el-pagination components

Use v-model to bind the paging information object. The paging information object includes 3 core attribute parameters. The paging event is directly bound to the method of querying data, eliminating the binding event methods of handleSizeChange and handleCurrentChange of the parent component.

1. Introduction

There are already many similar articles on the Internet about developing custom paging components by encapsulating el-pagination components, but after reading them, I was always dissatisfied, so I decided to make one myself.

2. Background

2.1. Conventional paging processing method

The general practice of using the el-pagination component is as follows:

Template part:

 <el-pagination @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :current-page="pageInfo.pagenum"
            :page-sizes="[5, 10, 15, 20]" :page-size="pageInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total"
            background>
        </el-pagination>

Script part:

export default {
  data() {
    return {
      formData : {
        //Query information queryInfo:{
          userType : 0,
          deleteFlag: 2, // indicates all types pagenum: 1,
          pagesize : 10      
        },

        // The user type selection box currently selects the displayed label value userTypeLabel: "all types",

        // The user status selection box currently displays the selected label value userStatusLabel: "all types"
      },
        
      // Paging information pageInfo:{
        pagenum : 1,
        pagesize : 10,
        total : 0
      }
    }
  },
  methods: {
    // Query user information list queryUsers(){
      let _this = this;
      //console.log(this.pageInfo);

      this.formData.queryInfo.pagenum = this.pageInfo.pagenum;
      this.formData.queryInfo.pagesize = this.pageInfo.pagesize;

      this.instance.queryUsers(
        this.$baseUrl,this.formData.queryInfo
      ).then(res => {
        //console.log(res.data);
        if (res.data.code == this.global.SucessRequstCode){
          //If the query is successful_this.pageInfo.total = res.data.data.length;
          _this.userInfoList = res.data.data;
        }else{
          alert(res.data.message);
        }
      }).catch(error => {
        alert('Query failed!');            
        console.log(error);
      });
    },    
    // Change the number of items per page handleSizeChange(newSize) {
        this.pageInfo.pagesize = newSize;
        this.queryUsers();
    },
    // The current page number changes handleCurrentChange(newPage) {
        this.pageInfo.pagenum = newPage;
        this.queryUsers();
    }
  }

2.2 Problem Analysis

Each paging query requires a set of similar methods, which are somewhat simple and repetitive, but also slightly different, that is, the method of querying data will be different.

For programmers with obsessive-compulsive disorder, simple and repetitive code is undoubtedly very unpleasant. Therefore, it needs to be componentized.

Analysis of el-pagination paging components:

  1. There are three core attribute parameters: current page number (current-page), number of records per page (page-size), and total number of records (total). The core attribute parameters implement bidirectional linkage by binding the parent component page data. The current page number and the number of records per page are generally changed by operating the paging subcomponent, and the total number of records is set by the parent component after querying the data.
  2. There are two events: @size-change (number of items per page changed event) and @current-change (current page number changed event). These two events are bound to the corresponding event processing methods handleSizeChange and handleCurrentChange of the parent component respectively. Both of them call the data query method. In the data query method, after obtaining the result set, the total number of records is set.

The development goal of the custom paging component is to eliminate the binding event methods of handleSizeChange and handleCurrentChange of the parent component.

Idea: Use v-model to bind the paging information object. The paging information object includes 3 core attribute parameters, namely the pageInfo mentioned above. Then the paging event is directly bound to the method of querying data.

3. Implementation of the plan

3.1. Custom paging components

Write a custom pagination component code, the file is /src/Pagination.vue. The code is as follows:

<template lang="html">
  <div class="pagination">
    <el-pagination 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange"
      :current-page.sync="pageInfo.pagenum"  
      :page-size="pageInfo.pagesize" 
      :page-sizes="pageSizes"
      :total="pageInfo.total"
      layout="total, sizes, prev, pager, next, jumper"
      background >
    </el-pagination>
  </div>   
</template>

<script>
  export default {
    name : "pagination",
    model : {
        prop : 'pageInfo',
        event : 'change'
    },
    props : {
      //Select the number of items per page pageSizes: {
        type: Array,
        default() {
          return [5, 10, 15, 20];
        }
      },
      // data object pageInfo bound to v-model: {
        type: Object,
        reuqired:true
      }
    },
    data(){
      return {            
      }
    },
    methods: {
      handleSizeChange(newSize) {
        var newValue={
					pagesize : newSize,
					pagenum : newSize <= this.total ? 1 : this.pageInfo['pagenum'] 
				};
        this.$emit('change',Object.assign(this.pageInfo,newValue));
        this.$emit('pagination');
      },
      handleCurrentChange(newPage) {
        this.$emit('change',Object.assign(this.pageInfo,{pagenum : newPage}));
        this.$emit('pagination');
      }
    }    
  }
</script>

<style lang="css" scoped>
.pagination {
    padding: 10px 0;
    text-align: center;
}
</style>

A custom paging component named pagination, which uses v-model to achieve two-way data communication. When the page number or the number of items per page changes, the pagination event @pagination is triggered, providing binding with the parent component method.

The field structure of pageInfo is stipulated as follows:

  pageInfo:{
        pagenum : 1, //Number
        pagesize : 10, //Number
        total : 0 //Number
      }

The parent component must provide a data object of the same structure to bind the pageInfo object inside the component.

3.2. Register the paging component

Then register this paging component and add the following code in main.js:

import pagination from '@/components/Pagination.vue'

//Register paging plugin Vue.component('pagination', pagination)

3.3. Parent component calling method

Modify the code in the previous Chapter 2 using the pagination component.

Template part:

  <!-- Paging area -->
        <pagination v-model="pageInfo" @pagination="queryUsers"></pagination>

Script part:

export default { 
  data() {
    return {
      formData : {
        //Query information queryInfo:{
          userType : 0,
          deleteFlag: 2, // indicates all types pagenum: 1,
          pagesize : 10      
        },

        // The user type selection box currently selects the displayed label value userTypeLabel: "all types",

        // The user status selection box currently displays the selected label value userStatusLabel: "all types"
      },
        
      // Paging information pageInfo:{
        pagenum : 1,
        pagesize : 10,
        total : 0
      }
    }
  },
  methods: {
    // Query user information list queryUsers(){
      let _this = this;
      //console.log(this.pageInfo);

      this.formData.queryInfo.pagenum = this.pageInfo.pagenum;
      this.formData.queryInfo.pagesize = this.pageInfo.pagesize;

      this.instance.queryUsers(
        this.$baseUrl,this.formData.queryInfo
      ).then(res => {
        //console.log(res.data);
        if (res.data.code == this.global.SucessRequstCode){
          //If the query is successful_this.pageInfo.total = res.data.data.length;
          _this.userInfoList = res.data.data;
        }else{
          alert(res.data.message);
        }
      }).catch(error => {
        alert('Query failed!');            
        console.log(error);
      });
    }
  }

In this way, the handleSizeChange and handleCurrentChange event response methods are removed. When the paging information changes, the bound queryUsers method is triggered.

In addition, if you need to adjust pageSizes, set it in the template as follows:

:pageSizes=[10,20,30,50,100]

4. References

The development of this component mainly refers to the following articles:

Vue+el-pagination secondary encapsulation, https://blog.csdn.net/weixin_47259997/article/details/107887823.

The vue project uses el-pagination in elementui to encapsulate the common paging component, https://www.jianshu.com/p/e241e5710fb0/.

This concludes this article about the entire process of Vue using v-model to encapsulate el-pagination components. For more relevant v-model encapsulation el-pagination component content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Example code of vue custom component to implement v-model two-way binding data
  • The use of v-model in vue3 components and in-depth explanation
  • Detailed explanation of the difference between v-model directive and .sync modifier in Vue
  • A brief discussion on the principle of Vue's two-way event binding v-model
  • Basic implementation method of cross-component binding using v-model in Vue
  • Problems and solutions encountered when using v-model to two-way bind the values ​​of parent-child components in Vue
  • Solution for Vue form input box not supporting focus and blur events
  • Detailed usage of Vue's form input component using custom events [Date component and currency component]
  • Example code for Vue form input binding
  • Vue form input formatting Chinese input method abnormality
  • Vue form input binding v-model

<<:  Learn the principles and common operations of MySQL partition tables through examples

>>:  How to add file prefixes in batches in Linux

Recommend

A graphic tutorial on how to install MySQL in Windows

Abstract: This article mainly explains how to ins...

Detailed explanation of uniapp's global variable implementation

Preface This article summarizes some implementati...

MYSQL database basics - Join operation principle

Join uses the Nested-Loop Join algorithm. There a...

WeChat applet implements calculator function

This article shares the specific code for the WeC...

How to run the springboot project in docker

1. Click Terminal below in IDEA and enter mvn cle...

Detailed explanation of how to install PHP7 on Linux

How to install PHP7 on Linux? 1. Install dependen...

Detailed explanation of Linux curl form login or submission and cookie usage

Preface This article mainly explains how to imple...

Two box models in web pages (W3C box model, IE box model)

There are two types of web page box models: 1: Sta...

MySQL log trigger implementation code

SQL statement DROP TRIGGER IF EXISTS sys_menu_edi...

JS realizes the case of eliminating stars

This article example shares the specific code of ...

MySQL Flush-List and dirty page flushing mechanism

1. Review The Buffer Pool will be initialized aft...

Vue backend management system implementation of paging function example

This article mainly introduces the implementation...

MySQL 8.0.16 installation and configuration graphic tutorial under macOS

This article shares the installation and configur...

Use momentJs to make a countdown component (example code)

Today I'd like to introduce a countdown made ...

MySQL compression usage scenarios and solutions

Introduction Describes the use cases and solution...