Home >Web Front-end >Vue.js >A brief analysis of how to use Vue3 to develop a Pagination public component

A brief analysis of how to use Vue3 to develop a Pagination public component

青灯夜游
青灯夜游forward
2021-11-19 19:48:533076browse

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!

A brief analysis of how to use Vue3 to develop a Pagination public component

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

A brief analysis of how to use Vue3 to develop a Pagination public component

Event

A brief analysis of how to use Vue3 to develop a Pagination public component

The effect after implementation

A brief analysis of how to use Vue3 to develop a Pagination public component

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

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 screenshot

After the test case is added

As shown below, the final test coverage is 100%

A brief analysis of how to use Vue3 to develop a Pagination public component

关于测试的总结

追求 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 &#39;vue&#39;;
export default definedComponent({
    emits: [&#39;update:currentPage&#39;],
    setup(props, { emit, slot, attrs }) {
        emit(&#39;update:currentPage&#39;);
        ...
    }
})

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: [&#39;update:currentPage&#39;],
    setup(props, { emit }) {
        当 Pagaintion 组件改变的时候,去触发 update:currentPage 就行
        emit(&#39;update:currentPage&#39;, 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: [&#39;update:currentPage&#39;, &#39;update:pageSize&#39;],
    setup(props, { emit }) {
        当 Pagaintion 组件改变的时候,去触发相应的事件就行
        emit(&#39;update:currentPage&#39;, newCurrentPage)
        emit(&#39;update:pageSize&#39;, newPageSize)
    }
})

Vue3 和 Vue2 v-model 比较

对于绑定单个属性来说感觉方便程度区别不大,而绑定多个值可以明显感觉 Vue3 的好处,不需要使用 sync 加 computed 里面去触发这种怪异的写法,直接用 v-model 统一,更加简便和易于维护。

reactive ref toRef toRefs 的实际使用

用 reactive 为对象添加响应式

实际组件中未使用,这里举例说明

import { reactive } from &#39;vue&#39;;

// setup 中
const data = reactive({
    count: 0
})
console.log(data.count); // 0

用 ref 给值类型数据添加响应式

jumper 文件中用来给用户输入的数据添加响应式

import {
    defineComponent, ref,
} from &#39;vue&#39;;
export default defineComponent({
    setup(props) {
        const current = ref(&#39;&#39;);
           return () => (
            <div>
                <FInput v-model={current.value}></FInput>
            </div>
        );
    },
});

当然,其实用 ref 给对象添加响应式也是可以的,但是每次使用的时候都需要带上一个value, 比如,变成 data.value.count 这样使用, 可以 ref 返回的数据是一个带有 value 属性的对象,本质是数据的拷贝,已经和原始数据没有关系,改变 ref 返回的值,也不再影响原始数据

import { ref } from &#39;vue&#39;;

// setup 中
const data = ref({
    count: 0
})
console.log(data.value.count); // 0

toRef

  • toRef 用于为源响应式对象上的属性新建一个 ref,从而保持对其源对象属性的响应式连接。接收两个参数:源响应式对象和属性名,返回一个 ref 数据,本质上是值的引用,改变了原始值也会改变

  • 实际组件并未使用,下面是举例说明

import { toRef } from &#39;vue&#39;;
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 &#39;解构&#39;出来
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: &#39;modelValue&#39;,
        isEqual: false,
    },
) => {
    const usingProp = config?.prop ?? &#39;modelValue&#39;;
    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 &#39;.../xxx&#39;

// setup 中
const [currentPage, updateCurrentPage] = useModel(props, emit, {
    prop: &#39;currentPage&#39;,
});

可以看到,我们可以清晰的看到 currentPage, updateCurrentPage 的来源。复用起来很简单快捷,pager、simpler 等页面的 v-model 都可以用上 这个 hook

computed、watch

感觉和 Vue2 中用法类似,不同点在于 Vue3 中使用的时候需要引入。 举例 watch 用法由于 currentPage 改变时候需要触发 change 事件,所以需要使用到 watch 功能

import { watch } from &#39;vue&#39;;

// setup 中
const [currentPage, updateCurrentPage] = useModel(props, emit, {
    prop: &#39;currentPage&#39;,
});
watch(currentPage, () => {
    emit(&#39;change&#39;, 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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete