Vue带Spinner自定义按钮:加载完成后状态重置问题咨询
自定义加载按钮状态重置:直接调用子组件方法实现
不用额外添加props监听或冗余变量,通过**组件引用(ref)**获取子组件实例,直接调用内部方法就能重置状态,具体步骤如下:
1. 父组件给按钮添加ref标记
在父组件模板中,给自定义按钮组件设置ref属性,用于后续获取组件实例:
<CustomButton ref="submitBtn" @click="triggerApiRequest">提交</CustomButton>
2. 子组件暴露状态重置方法
子组件内部维护loading状态,点击时先切换为加载状态并触发父组件的点击事件,同时将重置状态的方法暴露出去:
<template> <button :disabled="isLoading" @click="handleBtnClick"> <Spinner v-if="isLoading" /> <span v-else><slot></slot></span> </button> </template> <script setup> import { ref } from 'vue' const isLoading = ref(false) const emit = defineEmits(['click']) const handleBtnClick = () => { isLoading.value = true emit('click') } // 定义并暴露重置加载状态的方法 const stopLoading = () => { isLoading.value = false } defineExpose({ stopLoading }) </script>
3. 父组件请求完成后调用重置方法
在父组件的API请求逻辑中,无论请求成功还是失败,都在finally块里调用子组件的stopLoading方法,确保按钮状态一定会被重置:
<script setup> import { ref } from 'vue' const submitBtn = ref(null) const triggerApiRequest = async () => { try { // 发起API请求 await fetch('/api/your-endpoint', { method: 'POST', // 携带请求参数... }) // 请求成功后的业务逻辑,比如提示用户 } catch (err) { // 处理请求错误 console.error('请求失败:', err) } finally { // 调用子组件方法重置按钮状态 submitBtn.value?.stopLoading() } } </script>
关键细节提示
- 若使用Vue 2,无需
defineExpose,直接在子组件的methods中定义stopLoading,父组件通过this.$refs.submitBtn.stopLoading()调用即可 - 用
finally块包裹重置逻辑,能避免请求失败时按钮一直处于加载状态的问题
内容的提问来源于stack exchange,提问作者jackbailey
相关产品推荐
相关产品推荐

