fix: 🐛 修复 Collapse 使用 toggleAall 方法时不会触发 before-expand 钩子的问题 (#727)

This commit is contained in:
不如摸鱼去 2024-11-23 11:45:43 +08:00 committed by GitHub
parent 4bf8d1e300
commit 02aa5ceb78
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 305 additions and 189 deletions

View File

@ -54,20 +54,13 @@ const value = ref<string[]>(['item1'])
```html
<wd-collapse v-model="value">
<wd-collapse-item
v-for="(item, index) in itemList"
:before-expend="beforeExpend"
:key="index"
:title="item.title"
:name="item.name"
>
<wd-collapse-item v-for="(item, index) in itemList" :before-expend="beforeExpend" :key="index" :title="item.title" :name="item.name">
{{ item.body }}
</wd-collapse-item>
</wd-collapse>
```
```ts
import { useToast } from '@/uni_modules/wot-design-uni'
const toast = useToast()
const value = ref<string[]>(['item1'])
@ -152,6 +145,52 @@ Collapse 查看更多的模式下,可以使用插槽定义自己想要的折
</wd-collapse>
```
## 嵌套使用
`collapse`可以嵌套使用,同时由于`collapse-item`的内容容器存在默认的`padding`,所以嵌套的`collapse`需要设置`custom-body-style`或者`custom-body-class`来覆盖默认样式。
***以下为示例,也可以自行调整样式。***
:::tip 注意
`custom-body-style``custom-body-class``$LOWEST_VERSION$`及以上版本支持。
:::
```html
<view class="collapse">
<wd-collapse v-model="collapseRoot">
<wd-collapse-item custom-body-style="padding:0 0 0 14px" v-for="item in 5" :key="item" :title="`标签${item}`" :name="`${item}`">
<wd-collapse v-model="collapseList[item - 1]">
<wd-collapse-item
v-for="(item, index) in itemList"
:custom-class="index === 0 ? 'no-border' : ''"
:key="index"
:title="item.title"
:name="item.name"
>
{{ item.body }}
</wd-collapse-item>
</wd-collapse>
</wd-collapse-item>
</wd-collapse>
</view>
```
```css
.collapse {
:deep() {
.no-border {
&::after {
display: none;
}
}
}
}
```
```ts
const collapseRoot = ref<string[]>(['0'])
const collapseList = ref<Array<string[]>>([['item1'], ['item2'], ['item3'], ['item4'], ['item5']])
```
## CollapseItem Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | 最低版本 |
@ -159,7 +198,7 @@ Collapse 查看更多的模式下,可以使用插槽定义自己想要的折
| name | 折叠栏的标识符 | string | - | - | - |
| title | 折叠栏的标题, 支持同名 slot 自定义内容 | string | - | '' | - |
| disabled | 禁用折叠栏 | boolean | - | false | - |
| before-expend | 打开前的回调函数,返回 false 可以阻止打开,支持返回 Promise | Function | - | false | - |
| before-expend | 打开前的回调函数,返回 false 可以阻止打开,支持返回 Promise | Function | - | - | - |
### `before-expend` 执行时会传递以下回调参数:
@ -186,23 +225,61 @@ Collapse 查看更多的模式下,可以使用插槽定义自己想要的折
## Methods
| 方法名 | 说明 | 参数 | 最低版本 |
| --- | --- | --- | --- |
| toggleAll | 切换所有面板展开状态,传 `true` 为全部展开,`false` 为全部收起,不传参为全部切换 | _options?: boolean \| object_ | 0.2.6 |
| --------- | -------------------------------------------------------------------------------- | ------------------------------------ | -------- |
| toggleAll | 切换所有面板展开状态,传 `true` 为全部展开,`false` 为全部收起,不传参为全部切换 | `options?: CollapseToggleAllOptions` | 0.2.6 |
### CollapseToggleAllOptions 参数说明
| 参数名 | 说明 | 类型 | 默认值 |
| ------------ | ----------------------------------- | ------- | ------ |
| expanded | 是否展开true 为展开false 为收起 | boolean | - |
| skipDisabled | 是否跳过禁用项 | boolean | false |
### toggleAll 方法示例
```html
<wd-collapse ref="collapse">...</wd-collapse>
```
```ts
import { ref } from 'vue'
import type { CollapseInstance } from '@/uni_modules/wot-design-uni/components/wd-collapse/types'
const collapseRef = ref<CollapseInstance>()
// 全部切换
collapseRef.value?.toggleAll()
// 全部展开
collapseRef.value?.toggleAll(true)
// 全部收起
collapseRef.value?.toggleAll(false)
// 全部全部切换,并跳过禁用项
collapseRef.value?.toggleAll({
skipDisabled: true
})
// 全部选中,并跳过禁用项
collapseRef.value?.toggleAll({
expanded: true,
skipDisabled: true
})
```
## Collapse Slot
| name | 说明 | 最低版本 |
| ---- | ---------------------------------------------------- | -------- |
| title |标题,便于开发者自定义标题(非 viewmore 使用) | 1.2.27 |
| ----- | ---------------------------------------------------- | -------- |
| title | 标题,便于开发者自定义标题(非 viewmore 使用) | 1.2.27 |
| more | 查看更多,便于开发者自定义查看更多类型的展开收起样式 | - |
## CollapseItem 外部样式类
| 类名 | 说明 | 最低版本 |
| ------------ | ----------------------- | -------- |
| ----------------- | ------------------------------ | ---------------- |
| custom-class | collapseItem 根节点样式 | - |
| custom-body-style | 自定义折叠面板内容容器的样式 | $LOWEST_VERSION$ |
| custom-body-class | 自定义折叠面板内容容器的样式类 | $LOWEST_VERSION$ |
**注意:组件内插槽样式不生效,因此使用插槽时需注意添加外部样式类**
## Collapse 外部样式类

View File

@ -1,13 +1,19 @@
<template>
<view class="collapse">
<page-wraper>
<wd-toast></wd-toast>
<demo-block title="toggleAll" transparent>
<wd-button @click="collapse?.toggleAll()">toggleAll</wd-button>
<demo-block title="toggleAll">
<wd-button custom-class="custom-button" type="info" @click="collapse?.toggleAll()">全部切换</wd-button>
<wd-button custom-class="custom-button" type="success" @click="collapse?.toggleAll(true)">全部展开</wd-button>
<wd-button custom-class="custom-button" type="primary" @click="collapse?.toggleAll(false)">全部收起</wd-button>
<wd-button custom-class="custom-button" type="warning" @click="collapse?.toggleAll({ skipDisabled: true })">全部切换跳过禁用</wd-button>
<wd-button custom-class="custom-button" type="error" @click="collapse?.toggleAll({ expanded: true, skipDisabled: true })">
全部选中跳过禁用
</wd-button>
</demo-block>
<demo-block title="基础用法" transparent>
<wd-collapse ref="collapse" v-model="value1" @change="handleChange1">
<wd-collapse-item
:disabled="item.disabled"
v-for="(item, index) in itemList"
:before-expend="index === 2 ? beforeExpend : undefined"
:key="index"
@ -60,9 +66,15 @@
<demo-block title="嵌套" transparent>
<wd-collapse v-model="collapseRoot" @change="handleChange1">
<wd-collapse-item v-for="item in 5" :key="item" :title="`标签${item}`" :name="`${item}`">
<wd-collapse-item custom-body-style="padding:0 0 0 14px" v-for="item in 5" :key="item" :title="`标签${item}`" :name="`${item}`">
<wd-collapse v-model="collapseList[item - 1]">
<wd-collapse-item v-for="(item, index) in itemList" :key="index" :title="item.title" :name="item.name">
<wd-collapse-item
:custom-class="index === 0 ? 'no-border' : ''"
v-for="(item, index) in itemList"
:key="index"
:title="item.title"
:name="item.name"
>
{{ item.body }}
</wd-collapse-item>
</wd-collapse>
@ -89,6 +101,7 @@
</wd-collapse>
</demo-block>
</page-wraper>
</view>
</template>
<script lang="ts" setup>
import { useToast } from '@/uni_modules/wot-design-uni'
@ -105,7 +118,8 @@ const itemList = ref<Record<string, any>[]>([
{
title: '标签2',
name: 'item2',
body: '一般情况下,买家只能向商户申请退款,商户确认可以退款后,可以通过接口或者商户平台向微信支付发起退款申请。'
body: '一般情况下,买家只能向商户申请退款,商户确认可以退款后,可以通过接口或者商户平台向微信支付发起退款申请。',
disabled: true
},
{
title: '标签3',
@ -161,27 +175,6 @@ function handleChange7({ value }: any) {
console.log(value)
}
/**
function handleChange1({ value }: any) {
console.log(value)
}
function handleChange2({ value }: any) {
console.log(value)
}
function handleChange3({ value }: any) {
console.log(value)
}
function handleChange4({ value }: any) {
console.log(value)
}
function handleChange5({ value }: any) {
console.log(value)
}
function handleChange6({ value }: any) {
console.log(value)
}
/**
* 折叠面板展开前回调方法
* @param e
@ -205,7 +198,21 @@ function beforeExpend(name: string) {
}
</script>
<style lang="scss" scoped>
:deep(.more-slot) {
.collapse {
:deep(.more-slot) {
color: red;
}
:deep(.custom-button) {
margin-right: 16px;
margin-bottom: 16px;
}
:deep() {
.no-border {
&::after {
display: none;
}
}
}
}
</style>

View File

@ -270,7 +270,7 @@ $-checkbox-button-disabled-border: var(--wot-checkbox-button-disabled-border, rg
/* collapse */
$-collapse-side-padding: var(--wot-collapse-side-padding, $-size-side-padding) !default; // 左右间距
$-collapse-body-padding: var(--wot-collapse-body-padding, 14px 25px) !default; // body padding
$-collapse-body-padding: var(--wot-collapse-body-padding, 14px $-size-side-padding) !default; // body padding
$-collapse-header-padding: var(--wot-collapse-header-padding, 13px $-size-side-padding) !default; // 头部padding
$-collapse-title-color: var(--wot-collapse-title-color, rgba(0, 0, 0, 0.85)) !default; // 标题颜色
$-collapse-title-fs: var(--wot-collapse-title-fs, 16px) !default; // 标题字号

View File

@ -39,6 +39,11 @@
padding: $-collapse-header-padding;
overflow: hidden;
user-select: none;
@include when(expanded) {
@include halfPixelBorder('bottom');
}
}
@include e(title) {

View File

@ -1,10 +1,18 @@
import type { ComponentPublicInstance, ExtractPropTypes, PropType } from 'vue'
import { baseProps, makeBooleanProp, makeRequiredProp, makeStringProp } from '../common/props'
export type CollapseItemBeforeExpand = (name: string) => void
export type CollapseItemBeforeExpand = (name: string) => boolean | Promise<unknown>
export const collapseItemProps = {
...baseProps,
/**
*
*/
customBodyClass: makeStringProp(''),
/**
*
*/
customBodyStyle: makeStringProp(''),
/**
* , slot
*/
@ -33,7 +41,6 @@ export type CollapseItemExpose = {
getExpanded: () => boolean
/**
*
* @returns Promise<void>
*/
updateExpand: () => Promise<void>
}

View File

@ -1,13 +1,16 @@
<template>
<view :class="`wd-collapse-item ${disabled ? 'is-disabled' : ''} is-border ${customClass}`" :style="customStyle">
<view :class="`wd-collapse-item__header ${isFirst ? 'wd-collapse-item__header-first' : ''}`" @click="handleClick">
<view
:class="`wd-collapse-item__header ${expanded ? 'is-expanded' : ''} ${isFirst ? 'wd-collapse-item__header-first' : ''}`"
@click="handleClick"
>
<slot name="title" :expanded="expanded" :disabled="disabled" :isFirst="isFirst">
<text class="wd-collapse-item__title">{{ title }}</text>
<wd-icon name="arrow-down" :custom-class="`wd-collapse-item__arrow ${expanded ? 'is-retract' : ''}`" />
</slot>
</view>
<view class="wd-collapse-item__wrapper" :style="contentStyle" @transitionend="handleTransitionEnd">
<view class="wd-collapse-item__body" :id="collapseId">
<view class="wd-collapse-item__body" :class="customBodyClass" :style="customBodyStyle" :id="collapseId">
<slot />
</view>
</view>
@ -26,8 +29,8 @@ export default {
<script lang="ts" setup>
import wdIcon from '../wd-icon/wd-icon.vue'
import { computed, getCurrentInstance, onMounted, ref, watch, type CSSProperties } from 'vue'
import { addUnit, getRect, isArray, isDef, isPromise, objToStyle, requestAnimationFrame, uuid } from '../common/util'
import { computed, getCurrentInstance, onMounted, ref, type CSSProperties } from 'vue'
import { addUnit, getRect, isArray, isDef, isPromise, isString, objToStyle, requestAnimationFrame, uuid } from '../common/util'
import { useParent } from '../composables/useParent'
import { COLLAPSE_KEY } from '../wd-collapse/types'
import { collapseItemProps, type CollapseItemExpose } from './types'
@ -66,36 +69,40 @@ const contentStyle = computed(() => {
return objToStyle(style)
})
const selected = computed(() => {
if (collapse) {
return collapse.props.modelValue
} else {
return []
}
/**
* 是否选中
*/
const isSelected = computed(() => {
const modelValue = collapse ? collapse?.props.modelValue || [] : []
const { name } = props
return (isString(modelValue) && modelValue === name) || (isArray(modelValue) && modelValue.indexOf(name as string) >= 0)
})
onMounted(() => {
updateExpand()
updateExpand(isSelected.value)
})
function updateExpand() {
return getRect(`#${collapseId.value}`, false, proxy).then((rect) => {
async function updateExpand(useBeforeExpand: boolean = true) {
try {
if (useBeforeExpand) {
await handleBeforeExpand()
}
initRect()
} catch (error) {
/* empty */
}
}
function initRect() {
getRect(`#${collapseId.value}`, false, proxy).then((rect) => {
const { height: rectHeight } = rect
height.value = isDef(rectHeight) ? Number(rectHeight) : ''
const name = props.name
requestAnimationFrame(() => {
if (isDef(selected.value)) {
if (
(typeof selected.value === 'string' && selected.value === name) ||
(isArray(selected.value) && selected.value.indexOf(name as string) >= 0)
) {
if (isSelected.value) {
expanded.value = true
} else {
expanded.value = false
}
} else {
expanded.value = false
}
if (!inited.value) {
inited.value = true
}
@ -110,40 +117,44 @@ function handleTransitionEnd() {
}
//
function handleClick() {
async function handleClick() {
if (props.disabled) return
let name = props.name
const nexexpanded = !expanded.value //
if (nexexpanded) {
if (props.beforeExpend) {
const response: any = props.beforeExpend(name)
try {
await updateExpand()
const { name } = props
collapse && collapse.toggle(name, !expanded.value)
} catch (error) {
/* empty */
}
}
/**
* 展开前钩子
*/
function handleBeforeExpand() {
return new Promise<void>((resolve, reject) => {
const { name } = props
const nextexpanded = !expanded.value
if (nextexpanded && props.beforeExpend) {
const response = props.beforeExpend(name)
if (!response) {
return
reject()
}
if (isPromise(response)) {
response.then(() => {
handleChangeExpand(name)
response.then(() => resolve()).catch(reject)
} else {
resolve()
}
} else {
resolve()
}
})
} else {
handleChangeExpand(name)
}
} else {
handleChangeExpand(name)
}
} else {
handleChangeExpand(name)
}
}
function getExpanded() {
return expanded.value
}
function handleChangeExpand(name: string) {
updateExpand()
collapse && collapse.toggle(name, !expanded.value)
}
defineExpose<CollapseItemExpose>({ getExpanded, updateExpand })
</script>

View File

@ -52,7 +52,7 @@ export type CollapseExpose = {
* true false
* @param options
*/
toggleAll: (options?: boolean | CollapseToggleAllOptions) => void
toggleAll: (options?: CollapseToggleAllOptions) => void
}
export type CollapseInstance = ComponentPublicInstance<CollapseProps, CollapseExpose>

View File

@ -45,7 +45,7 @@ import wdIcon from '../wd-icon/wd-icon.vue'
import { onBeforeMount, ref, watch } from 'vue'
import { COLLAPSE_KEY, collapseProps, type CollapseExpose, type CollapseToggleAllOptions } from './types'
import { useChildren } from '../composables/useChildren'
import { isArray, isDef } from '../common/util'
import { isArray, isBoolean, isDef } from '../common/util'
import { useTranslate } from '../composables/useTranslate'
const props = defineProps(collapseProps)
@ -94,10 +94,22 @@ function updateChange(activeNames: string | string[] | boolean) {
})
}
function toggle(name: string, expanded: boolean) {
//
const updateChildren = async () => {
for (const item of children) {
try {
await item.$.exposed!.updateExpand()
} catch (error) {
console.warn(`更新折叠面板状态失败: ${error}`)
}
}
}
async function toggle(name: string, expanded: boolean) {
const { accordion, modelValue } = props
if (accordion) {
updateChange(name === modelValue ? '' : name)
await updateChildren()
} else if (expanded) {
updateChange((modelValue as string[]).concat(name))
} else {
@ -109,30 +121,27 @@ function toggle(name: string, expanded: boolean) {
* 切换所有面板展开状态 true 为全部展开false 为全部收起不传参为全部切换
* @param options 面板状态
*/
const toggleAll = (options: boolean | CollapseToggleAllOptions = {}) => {
const toggleAll = async (options: CollapseToggleAllOptions = {}) => {
if (props.accordion) {
return
}
if (typeof options === 'boolean') {
if (isBoolean(options)) {
options = { expanded: options }
}
const { expanded, skipDisabled } = options
const names: string[] = []
children.forEach((item, index: number) => {
children.forEach((item, index) => {
if (item.disabled && skipDisabled) {
if (item.$.exposed!.getExpanded()) {
names.push(item.name || index)
}
} else {
item.$.exposed!.updateExpand()
if (isDef(expanded) ? expanded : !item.$.exposed!.getExpanded()) {
} else if (isDef(expanded) ? expanded : !item.$.exposed!.getExpanded()) {
names.push(item.name || index)
}
}
})
updateChange(names)
await updateChildren()
}
/**