


A brief analysis of how to use Vue3 to develop a Pagination public component
How to use Vue3 to develop a Pagination public component? The following article will introduce to you the method of encapsulating a Pagination public component based on Vue3. I hope it will be helpful to you!
Recently, I had the honor to participate in the development of our department's public component library based on vue3. I will record some experiences of the actual use process of vue3, as well as some issues to pay attention to when developing public components. [Related recommendations: "vue.js Tutorial"]
Function to be implemented
Attribute
Event
The effect after implementation
Theoretical development process
We use test-driven development (TDD) development process is
Write documents corresponding to function points
Write unit tests corresponding to function points
Run the test case to ensure that the case fails
Write code to implement
-
Run the test case to ensure that the case succeeds
Actual development process
Knowledge points that need to be mastered before development
New features of Vue3
-
Test with jest, @vue/test-utils: 2.0.0-rc.6 Test Vue components
jsx syntax
Organizational Structure
Project Organizational Structure
Organizational Structure Referencevitepress Document
Write corresponding function points The document
is mainly based on the UI renderings given by the designer, combined with the functional points in other excellent UI libraries, and finally discusses the effects we need to achieve, and finally writes the document.
Test case writing
4 indicators of test coverage
行覆盖率(line coverage):每个可执行代码行是否都执行了? 函数覆盖率(function coverage):每个函数是否都调用了? 分支覆盖率(branch coverage):每个流程控制的各个分支是否都执行了? 语句覆盖率(statement coverage):每个语句是否都执行了?
How to write test cases
Test-driven development requires that test case writing takes precedence over the implementation of unit functions. This requires first thinking about how to split the components and what functions each part needs after splitting.
Test these imaginary functions. However, during the actual development process, it was found that it was difficult to achieve a relatively high test coverage by writing test cases before the functions were developed, so we had to supplement the tests after the function development was completed.
pagination component structure
The following is the organizational structure I gave before writing the function. The function is implemented in jumper, pager, pagination, simpler, sizes, total and other jsx files
- _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 writing test cases for the jumper function
The tests for other parts are also similar
ShowQuickJumper Jumper related functions will be displayed only when the tree shape is true, and judging whether jumper is displayed can be achieved by whether the rendered component has a special jumper related class. The classes api in @vue/test-utils is very It is good to achieve such an effect.
A test for problems such as when the value entered by the jumper is not a number, the number exceeds the boundary, or the number is NaN.
Functional test, when the input is completed and the focus is lost, whether it can jump to the corresponding page.
Achieved test coverage
No test will pass until the function is completed
#After the function is completed
The test coverage is less than 70%, but unfortunately I forgot to take a screenshotAfter the test case is added
As shown below, the final test coverage is 100%关于测试的总结
追求 100% 的测试覆盖率是否有必要呢?
非常有必要,因为在追求 100% 的测试覆盖率的时候我回去审查每一行代码,看实际过程中是否每一行代码都可以覆盖到,而在这个过程中发现了一些冗余代码,比如说我已经在 jumper.jsx 里面已经对回传 pagination.jsx 中的数据进行了一个处理,确保里面不会产生非数字,且不会超出边界,而又在 pagination.jsx 中处理了一遍, 这样导致 pagination 里面的处理变得多余,而永远不会执行。因为每一行,每一个分支都可以执行到,这样也可以有效的减少潜在的 bug。
功能实现过程遇到的问题
样式规范
需要兼容切换风格、后期可能会调整字体颜色、按钮大小、按钮之间的距离等,开发的时候所有颜色、常规的一些距离等等都需要再公共文件里面取。这样每一个小的样式都需要思考是否必须,是否需要在库里取,开发过程可能会比直接写颜色等要慢一些。
所以可能带有的 class 都要有 is 属性,is-disabled、is-double-jumper 啥的
尽量不用元素选择器,一个是效率低,一个是变更时候容易照成必须要的影响
js 规范
jsx 里面使用 bind 绑定事件时候,如果里面的第一个参数没有意义,直接设为 null 即可,handleXxx.bind(null, aaa)
jsx 语句尽量格式化,简短一点
// setup 里面 // 不好的写法 return ( <div> {simple.value ? <Simple xxx /> : <Pager xxx/>} <div> ) // 好的写法 const renderPage = () => { if (simple.value) { return <Simele xxx/>; } return <Pager xxx/> } return ( <div> {renderPage()} </div> )
功能的功能尽量封装成 hooks, 比如实现 v-model
vue3 新特性的实际使用
setup 参数
setup 函数接受两个参数,一个是 props, 一个是 context
props 参数
不能用 es6 解构,解构出来的数据会失去响应式,一般会使用 toRef 或者 toRefs 去处理
context 参数
该参数包含 attrs、slot、emit,如果里面需要使用到某个 emit,则要在 emits 配置中声明
import { definedComponent } from 'vue'; export default definedComponent({ emits: ['update:currentPage'], setup(props, { emit, slot, attrs }) { emit('update:currentPage'); ... } })
v-model 使用
pageSize 和 currentPage 两个属性都需要实现 v-model。
vue2 实现双向绑定的方式
vue 2 实现自定义组件一到多个v-model双向数据绑定的方法
https://blog.csdn.net/Dobility/article/details/110147985
vue3 实现双向绑定的方式
实现单个数据的绑定
假如只需要实现 currentPage 双向绑定, vue3 默认绑定的是 modelValue 这个属性
// 父组件使用时候 <Pagination v-model="currentPage" /> // 相当于 <Pagination :modelValue="currentPage" @update:modelValue="(val) => {currentPage = val}" /> // Pagination 组件 import { defineComponent } from vue; export default defineComponent({ props: { currentPage: { type: Number, default: 1 } } emits: ['update:currentPage'], setup(props, { emit }) { 当 Pagaintion 组件改变的时候,去触发 update:currentPage 就行 emit('update:currentPage', newCurrentPage) } })
实现多个数据的绑定
pageSize 和 currentPage 两个属性都需要实现 v-model
// 父组件使用时候 <Pagination v-model:currentPage="currentPage" v-model:pageSize="pageSize" /> // Pagination 组件 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 }) { 当 Pagaintion 组件改变的时候,去触发相应的事件就行 emit('update:currentPage', newCurrentPage) emit('update:pageSize', newPageSize) } })
Vue3 和 Vue2 v-model 比较
对于绑定单个属性来说感觉方便程度区别不大,而绑定多个值可以明显感觉 Vue3 的好处,不需要使用 sync 加 computed 里面去触发这种怪异的写法,直接用 v-model 统一,更加简便和易于维护。
reactive ref toRef toRefs 的实际使用
用 reactive 为对象添加响应式
实际组件中未使用,这里举例说明
import { reactive } from 'vue'; // setup 中 const data = reactive({ count: 0 }) console.log(data.count); // 0
用 ref 给值类型数据添加响应式
jumper 文件中用来给用户输入的数据添加响应式
import { defineComponent, ref, } from 'vue'; export default defineComponent({ setup(props) { const current = ref(''); return () => ( <div> <FInput v-model={current.value}></FInput> </div> ); }, });
当然,其实用 ref 给对象添加响应式也是可以的,但是每次使用的时候都需要带上一个value, 比如,变成 data.value.count 这样使用, 可以 ref 返回的数据是一个带有 value 属性的对象,本质是数据的拷贝,已经和原始数据没有关系,改变 ref 返回的值,也不再影响原始数据
import { ref } from 'vue'; // setup 中 const data = ref({ count: 0 }) console.log(data.value.count); // 0
toRef
toRef 用于为源响应式对象上的属性新建一个 ref,从而保持对其源对象属性的响应式连接。接收两个参数:源响应式对象和属性名,返回一个 ref 数据,本质上是值的引用,改变了原始值也会改变
实际组件并未使用,下面是举例说明
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 用于将响应式对象转换为结果对象,其中结果对象的每个属性都是指向原始对象相应属性的 ref。常用于es6的解构赋值操作,因为在对一个响应式对象直接解构时解构后的数据将不再有响应式,而使用 toRefs 可以方便解决这一问题。本质上是值的引用,改变了原始值也会改变
// setup 中 const { small, pageSizeOption, totalCount, simple, showSizeChanger, showQuickJumper, showTotal, } = toRefs(props); // 这样就可以把里面所有的 props '解构'出来 console.log(small.value)
由于 props 是不能用 es6 解构的,所以必须用 toRefs 处理
四种给数据添加响应式的区别
是否是原始值的引用
reactive、toRef、toRefs 处理返回的对象是原始对象的引用,响应式对象改变,原始对象也会改变,ref 则是原始对象的拷贝,和原始对象已经没有关系。
如何取值
ref、toRef、toRefs 返回的响应式对象都需要加上 value, 而 reactive 是不需要的
作用在什么数据上
reactive 为普通对象;ref 值类型数据;toRef 响应式对象,目的为取出某个属性; toRefs 解构响应式对象;
用 vue3 hooks 代替 mixins
如果想要复用是一个功能,vue2 可能会采用 mixins 的方法,mixins 有一个坏处,来源混乱,就是有多个 mixin 的时候,使用时不知道方法来源于哪一个 mixins。而 Vue3 hooks 可以很好解决这一个问题。我们把 v-model 写成一个 hook
const useModel = ( props, emit, config = { prop: 'modelValue', isEqual: false, }, ) => { const usingProp = config?.prop ?? 'modelValue'; const currentValue = ref(props[usingProp]); 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]; }; // 使用的时候 import useModel from '.../xxx' // setup 中 const [currentPage, updateCurrentPage] = useModel(props, emit, { prop: 'currentPage', });
可以看到,我们可以清晰的看到 currentPage, updateCurrentPage 的来源。复用起来很简单快捷,pager、simpler 等页面的 v-model 都可以用上 这个 hook
computed、watch
感觉和 Vue2 中用法类似,不同点在于 Vue3 中使用的时候需要引入。 举例 watch 用法由于 currentPage 改变时候需要触发 change 事件,所以需要使用到 watch 功能
import { watch } from 'vue'; // setup 中 const [currentPage, updateCurrentPage] = useModel(props, emit, { prop: 'currentPage', }); watch(currentPage, () => { emit('change', currentPage.value); })
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of A brief analysis of how to use Vue3 to develop a Pagination public component. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



vue3+vite:src uses require to dynamically import images and error reports and solutions. vue3+vite dynamically imports multiple images. If vue3 is using typescript development, require will introduce image errors. requireisnotdefined cannot be used like vue2 such as imgUrl:require(' .../assets/test.png') is imported because typescript does not support require, so import is used. Here is how to solve it: use awaitimport

tinymce is a fully functional rich text editor plug-in, but introducing tinymce into vue is not as smooth as other Vue rich text plug-ins. tinymce itself is not suitable for Vue, and @tinymce/tinymce-vue needs to be introduced, and It is a foreign rich text plug-in and has not passed the Chinese version. You need to download the translation package from its official website (you may need to bypass the firewall). 1. Install related dependencies npminstalltinymce-Snpminstall@tinymce/tinymce-vue-S2. Download the Chinese package 3. Introduce the skin and Chinese package. Create a new tinymce folder in the project public folder and download the

To achieve partial refresh of the page, we only need to implement the re-rendering of the local component (dom). In Vue, the easiest way to achieve this effect is to use the v-if directive. In Vue2, in addition to using the v-if instruction to re-render the local dom, we can also create a new blank component. When we need to refresh the local page, jump to this blank component page, and then jump back in the beforeRouteEnter guard in the blank component. original page. As shown in the figure below, how to click the refresh button in Vue3.X to reload the DOM within the red box and display the corresponding loading status. Since the guard in the component in the scriptsetup syntax in Vue3.X only has o

Vue implements the blog front-end and needs to implement markdown parsing. If there is code, it needs to implement code highlighting. There are many markdown parsing libraries for Vue, such as markdown-it, vue-markdown-loader, marked, vue-markdown, etc. These libraries are all very similar. Marked is used here, and highlight.js is used as the code highlighting library. The specific implementation steps are as follows: 1. Install dependent libraries. Open the command window under the vue project and enter the following command npminstallmarked-save//marked to convert markdown into htmlnpmins

After the vue3 project is packaged and published to the server, the access page displays blank 1. The publicPath in the vue.config.js file is processed as follows: const{defineConfig}=require('@vue/cli-service') module.exports=defineConfig({publicPath :process.env.NODE_ENV==='production'?'./':'/&

The final effect is to install the VueCropper component yarnaddvue-cropper@next. The above installation value is for Vue3. If it is Vue2 or you want to use other methods to reference, please visit its official npm address: official tutorial. It is also very simple to reference and use it in a component. You only need to introduce the corresponding component and its style file. I do not reference it globally here, but only introduce import{userInfoByRequest}from'../js/api' in my component file. import{VueCropper}from'vue-cropper&

vue3+ts+axios+pinia realizes senseless refresh 1. First download aiXos and pinianpmipinia in the project--savenpminstallaxios--save2. Encapsulate axios request-----Download js-cookienpmiJS-cookie-s//Introduce aixosimporttype{AxiosRequestConfig ,AxiosResponse}from"axios";importaxiosfrom'axios';import{ElMess

Preface Whether it is vue or react, when we encounter multiple repeated codes, we will think about how to reuse these codes instead of filling a file with a bunch of redundant codes. In fact, both vue and react can achieve reuse by extracting components, but if you encounter some small code fragments and you don’t want to extract another file, in comparison, react can be used in the same Declare the corresponding widget in the file, or implement it through renderfunction, such as: constDemo:FC=({msg})=>{returndemomsgis{msg}}constApp:FC=()=>{return(
