新建组件
<template>
<el-button :loading="loading" v-bind="props" @click="handleClick">
<slot></slot>
</el-button>
</template>
<script setup lang="ts">
import { ButtonGroupProps } from 'element-plus/es/components/button/src/button-group.mjs'
defineOptions({
inheritAttrs: false
})
const props = defineProps<Omit<ButtonGroupProps, 'loading'>>()
const attrs = useAttrs()
const loading = ref(false)
const handleClick = async () => {
loading.value = true
try {
await (attrs as any)?.onClick?.()
} finally {
loading.value = false
}
}
</script>
页面使用
import ELButton from '@/components/ELButton/index.vue'
<ELButton type="primary" @click="loadingClick">点击loading</ELButton>
补充:vue2版(非ts)
<template>
<el-button :loading="btnLoading" v-bind="$attrs" @click="handleClick">
<slot></slot>
</el-button>
</template>
<script>
export default {
inheritAttrs: false,
data() {
return {
btnLoading: false
}
},
methods: {
async handleClick() {
this.btnLoading = true
try {
if (this.$listeners.click) {
await this.$listeners.click()
}
} finally {
this.btnLoading = false
}
}
}
}
</script>
vantui版本:
<template>
<van-button v-bind="$attrs" :loading="loading" @click="handleClick">
<slot></slot>
</van-button>
</template>
<script setup lang="ts">
const props = defineProps<{
onClick?: () => Promise<void> | void
}>()
const loading = ref(false)
async function handleClick() {
loading.value = true
try {
await props.onClick?.() // 明确使用 props 而不是 attrs
} finally {
loading.value = false
}
}
</script>
感谢你的阅读,如对你有帮助请收藏+关注!
只分享干货实战和精品,从不啰嗦!!!
如某处不对请留言评论,欢迎指正~
博主可收徒、常玩QQ飞车,可一起来玩玩鸭~