在vue中如何優(yōu)雅的處理loading

以下這段代碼中,是有個(gè)按鈕,有個(gè)loading ,綁定點(diǎn)擊事件,模擬請求完成后loading為true

<template>
  <div>
    <el-button :loading="loading" @click="onClick"></el-button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const loading = ref(false)
async function onClick() {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
  } finally {
    loading.value = false
  }
}
</script>

上述代碼中能不能進(jìn)行優(yōu)化,能不能封裝這個(gè)組件,在這個(gè)組件內(nèi)部來處理這個(gè)問題,在需要的地方直接調(diào)這個(gè)按鈕的組件就可以了
index.vue的代碼如下:

<template>
  <div>
    <MyButton type="primary" @click="onclick">按鈕</MyButton>
  </div>
</template>

<script setup lang="ts">
import MyButton from './MyButton.vue';
async function onclick() {
  console.log('點(diǎn)擊按鈕')
  await new Promise(resolve => setTimeout(resolve, 1000))
}
</script>

MyButton組件代碼如下

<template>
  <div>
    <!-- <el-button :loading="loading" v-bind="$attrs" @click="onClick">
      <slot></slot>
    </el-button> -->
    <el-button :loading="loading" v-bind="props" @click="onClick">
      <slot></slot>
    </el-button>
  </div>
</template>
<script setup lang="ts">
import { ref,useAttrs } from 'vue'
import type { ButtonProps } from 'element-plus'
defineOptions({
  inheritAttrs: false, //不繼承父組件的屬性
})
//這個(gè)attrs是跟$attrs是一樣的是用來接收父組件傳遞過來的所有屬性
const attrs = useAttrs()
console.log("attrs===>:",attrs)
const loading = ref(false)
//去除里面的loading屬性
const props = defineProps<Partial<Omit<ButtonProps,'loading'>>>()
async function onClick() {
  loading.value = true
  try {
    // await new Promise(resolve => setTimeout(resolve, 1000))
    //通過attrs獲取父組件傳遞過來onclick方法
    console.log('調(diào)用外部點(diǎn)擊事件')
    //@ts-ignore
    await attrs?.onClick?.()
  } finally {
    loading.value = false
  }
 
}
</script>

以上buttom組件的loading封裝完成了,比如要二次封裝表格,然后傳的函數(shù)是異步的,只要是異步,涉及到loading的都可以去封裝一下

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容