Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Vue3 to develop a Pagination common component

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use Vue3 to develop a Pagination common component". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use Vue3 to develop a Pagination common component".

Functional attributes to be implemented

Event

The effect after realization

Theoretical development process

We are using the test-driven development (TDD) development process as follows

Write the document corresponding to the function point

Write the unit test of the corresponding function point

Run the test case to make sure the case fails

Write code to implement

Run test cases to ensure the success of the case

Knowledge points that need to be mastered before the actual development process

New features of Vue3

Test the Vue component with jest test, @ vue/test-utils: 2.0.0-rc.6

Jsx syntax

Organizational structure project organizational structure

Organizational structure reference vitepress documentation

Write the document corresponding to the function point

Mainly according to the UI effect diagram given by the designer, combined with the function points of other excellent UI libraries, finally discuss the effect we need to achieve, and finally write the document.

Test case Writing 4 Metrics Line coverage (line coverage) of test coverage: is each line of executable code executed? Function coverage (function coverage): is every function called? Branch coverage (branch coverage): is each branch of each process control implemented? Statement coverage (statement coverage): is every statement executed? How to write test cases

Test-driven development requires that test case writing takes precedence over the implementation of unit functions, so we need to think about how to split the components and what functions are needed for each part after the split.

Test these imaginary functions. However, in the actual development process, it is difficult to write test cases before the function is developed, so we have to supplement the test after the completion of the function development.

The structure of pagination components

The following is the organizational structure I gave before writing the function, which is implemented in the jsx files such as jumper, pager, pagination, simpler, sizes, total, etc.

-_ tests_-pagination.js- style-index.js- index.less-mixin.less- const.js- index.js- jumper.jsx- pager.jsx- pagination.jsx- simpler.jxs- sizes.jsx- total.jsx examples of test cases for jumper functions

Other parts of the test are similar.

Jumper-related features will only be displayed when the ShowQuickJumper tree is true. To determine whether the jumper display can be achieved by whether the rendered component has a special jumper-related class, the classes api in @ vue/test-utils can achieve such an effect.

A test when the value entered by jumper is not a number, the number is beyond the boundary, the number is NaN, and so on.

Functional test, whether you can jump to the appropriate page when the input is complete and you lose focus.

Before the completion of the achieved test coverage function

None of the tests passed.

After the completion of the function

Test coverage is less than 70%. Unfortunately, I forgot to take screenshots.

After the test cases are supplemented

As shown in the figure below, the final test coverage is 100%.

Is it necessary for a summary of tests to pursue 100% test coverage?

It is very necessary, because in pursuit of 100% test coverage, I go back to review every line of code to see if every line of code can be covered in the actual process, and found some redundant code in the process. For example, I have already done a processing on the data in the backhaul pagination.jsx in jumper.jsx to make sure that there are no non-numbers in it and that it does not exceed the boundary. It is processed again in pagination.jsx, which causes the processing in pagination to become redundant and never executed. Because every line and every branch can be executed, it can also effectively reduce the potential bug.

The style specification of the problems encountered in the process of function implementation

Need to be compatible with switching styles, later may adjust the font color, button size, distance between buttons, etc., all colors, regular distances, and so on need to be taken in the public file. In this way, each small style needs to think about whether it is necessary, whether it needs to be taken from the library, and the development process may be slower than writing colors directly.

So all possible class should have is attributes, such as is-disabled, is-double-jumper and so on.

Try not to use element selectors, one is inefficient, and the other is easy to capture the necessary influence when changing.

Js specification

When the bind binding event is used in jsx, if the first parameter in it is meaningless, just set it to null, handleXxx.bind (null, aaa)

Jsx statements should be formatted as much as possible and be brief.

/ / in setup / / bad writing return ({simple.value?:}) / / good writing const renderPage = () = > {if (simple.value) {return;} return} return ({renderPage ()})

The functions of the functions are encapsulated as hooks as possible, such as implementing v-model

Actual use of setup parameters for new features of vue3

The setup function takes two arguments, one is props and the other is context

Props parameter

Can not be deconstructed with es6, the deconstructed data will lose the response, generally will use toRef or toRefs to deal with

Context parameter

This parameter contains attrs, slot and emit. If you need to use an emit in it, declare it in the emits configuration.

Import {definedComponent} from 'vue';export default definedComponent ({emits: [' update:currentPage'], setup (props, {emit, slot, attrs}) {emit ('update:currentPage');.}}) v-model use

Both the pageSize and currentPage properties need to implement v-model.

The way of realizing two-way binding by vue2

The method of implementing one or more v-model two-way data binding of custom components in vue 2

Https://blog.csdn.net/Dobility/article/details/110147985

Vue3 implements two-way binding to realize the binding of single data.

If you only need to implement currentPage two-way binding, vue3 will bind the attribute modelValue by default.

/ / parent component in use / / equivalent to / / Pagination component import {defineComponent} from vue Export default defineComponent ({props: {currentPage: {type: Number, default: 1}} emits: ['update:currentPage'], setup (props, {emit}) {when the Pagaintion component changes, just trigger update:currentPage (' update:currentPage', newCurrentPage)}}) to bind multiple data

Both pageSize and currentPage properties need to implement v-model

/ / parent component in use / / Pagination component import {defineComponent} from vue Export default defineComponent ({pageSize: {type: Number, default: 10,}, currentPage: {type: Number, default: 1,}, emits: ['update:currentPage',' update:pageSize'], setup (props, {emit}) {when Pagaintion components change To trigger the corresponding event, just compare emit ('update:currentPage', newCurrentPage) emit (' update:pageSize', newPageSize)}) Vue3 and Vue2 v-model

For binding a single attribute, there is little difference in convenience, while binding multiple values can obviously feel the benefits of Vue3, there is no need to use sync plus computed inside to trigger this strange way of writing, directly use v-model unified, more simple and easy to maintain.

The actual use of reactive ref toRef toRefs uses reactive to add responsiveness to objects

It is not used in the actual component. Here is an example.

Const data = reactive ({count: 0}) console.log (data.count) in import {reactive} from 'vue';// setup; / / 0 add responsiveness to value type data with ref

The jumper file is used to add responsiveness to the data entered by the user

Import {defineComponent, ref,} from 'vue';export default defineComponent ({setup (props) {const current = ref (''); return () = > ();},})

Of course, its practical ref can also add responsiveness to objects, but each time you use it, you need to bring a value. For example, if you use it like data.value.count, the data returned by ref is an object with value attribute, which is essentially a copy of the data, which has nothing to do with the original data. Changing the value returned by ref will no longer affect the original data.

Const data = ref ({count: 0}) console.log (data.value.count) in import {ref} from 'vue';// setup; / / 0toRef

ToRef is used to create a new ref for the properties on the source responsive object, thus maintaining a responsive connection to its source object properties. Receives two parameters: the source responsive object and the property name, and returns an ref data, which is essentially a reference to the value, which will change if the original value is changed.

The actual component is not used, here is an example

Import {toRef} from 'vue';export default {props: {totalCount: {type: number, default: 0}}, setup (props) {const myTotalCount = toRef (props, totalCount); console.log (myTotalCount.value);} toRefs

ToRefs is used to convert responsive objects into result objects, where each property of the result object is a ref that points to the corresponding property of the original object. It is often used in the deconstruction assignment operation of es6, because the deconstructed data will no longer be responsive when directly deconstructing a responsive object, but using toRefs can easily solve this problem. It is essentially a reference to the value, and if the original value is changed, it will also change.

/ / const {small, pageSizeOption, totalCount, simple, showSizeChanger, showQuickJumper, showTotal,} = toRefs (props) in setup; / / so that all props in it can be 'deconstructed' out of console.log (small.value)

Since props cannot be deconstructed with es6, it must be processed with toRefs

Are the four differences in adding responsiveness to data a reference to the original value

The object returned by reactive, toRef and toRefs is a reference to the original object. If the responsive object changes, the original object will also change, while ref is a copy of the original object, which has nothing to do with the original object.

How to take a value

Value is required for responsive objects returned by ref, toRef and toRefs, but reactive is not required.

What data does it work on?

Reactive is a normal object; ref value type data; toRef responsive object in order to extract an attribute; toRefs deconstructs responsive object

Replace mixins with vue3 hooks

If you want to reuse is a function, vue2 may adopt the mixins method, mixins has a disadvantage, the source is confusing, that is, when there are multiple mixin, you do not know which mixins the method comes from. And Vue3 hooks can solve this problem very well. Let's write v-model as a hook.

Const useModel = (props, emit, config = {prop: 'modelValue', isEqual: false,},) = > {const usingProp = config?.prop? 'modelValue'; const currentValue = ref (props[ propingProp]); const updateCurrentValue = (value) = > {if (value = currentValue.value | | (config.isEqual & & isEqual (value, currentValue.value)) {return;} currentValue.value = value;}; watch (currentValue, () = > {emit (`update:$ {usingProp} `, currentValue.value);}) Watch (() = > props [usingProp], (val) = > {updateCurrentValue (val);},); return [currentValue, updateCurrentValue];}; / / when in use, const [currentPage, updateCurrentPage] in import useModel from '... / xxx'// setup = useModel (props, emit, {prop:' currentPage',})

As you can see, we can clearly see the source of currentPage and updateCurrentPage. Reuse is very simple and quick, and this hook can be used in v-model of pager, simpler and other pages.

Computed 、 watch

It feels similar to the usage in Vue2, except that it needs to be introduced when used in Vue3. Example watch usage because the change event needs to be triggered when currentPage changes, so you need to use the watch function

Const [currentPage, updateCurrentPage] = useModel (props, emit, {prop: 'currentPage',}) in import {watch} from' vue';// setup; watch (currentPage, () = > {emit ('change', currentPage.value)) }) Thank you for reading, the above is the content of "how to use Vue3 to develop a Pagination common component". After the study of this article, I believe you have a deeper understanding of how to use Vue3 to develop a Pagination common component, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 285

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report