Element Plus 的 Loading 组件怎么在按钮点击后不显示?

Zz乐佳 阅读 103

我在用 Element Plus 的 Loading,想在点击按钮时显示加载状态,但调用后完全没反应。试过用指令方式 v-loading="loading",也试过服务方式 this.$loading(),都不行。

这是我的代码:

<template>
  <el-button @click="handleClick" v-loading="loading">提交</el-button>
</template>

<script setup>
import { ref } from 'vue'
const loading = ref(false)
const handleClick = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 2000)
}
</script>
我来解答 赞 10 收藏
二维码
手机扫码查看
2 条解答
淑怡
淑怡 Lv1
Element Plus跟WordPress没啥关系,不过这问题我也遇到过。你的代码其实挺接近正确的了,就是少了个关键点。v-loading指令要用在容器元素上,而不是直接用在按钮上。

给你个修正版的:

<template>
<div v-loading="loading">
<el-button @click="handleClick">提交</el-button>
</div>
</template>

<script setup>
import { ref } from 'vue'
const loading = ref(false)
const handleClick = () => {
loading.value = true
setTimeout(() => {
loading.value = false
}, 2000)
}
</script>


这样改完就能正常显示加载状态了。说真的,这些UI框架有时候设计得有点反直觉,我之前也在这上面卡了半天。WP里面倒是没这种问题,毕竟都是现成的钩子函数,直接调用就完事。
点赞
2026-03-27 08:11
慕容旗施
你的问题大概率是没注册 Loading 指令。v-loading 指令需要单独注册,不是自动生效的。

在 main.ts 里加上:

import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { LoadingDirective } from 'element-plus'

const app = createApp(App)
app.use(ElementPlus)
app.directive('loading', LoadingDirective) // 这行不能少
app.mount('#app')


如果你是按需引入的方式注册组件,也需要单独处理指令:

import { defineComponent } from 'vue'
import { ElButton, ElLoading } from 'element-plus'

export default defineComponent({
components: { ElButton },
directives: { loading: ElLoading.directive }, // 指令注册
setup() {
const loading = ref(false)
const handleClick = () => {
loading.value = true
setTimeout(() => {
loading.value = false
}, 2000)
}
return { loading, handleClick }
}
})


如果你不想折腾指令注册,直接用服务方式更省事:

import { ElLoading } from 'element-plus'

const handleClick = () => {
const loadingInstance = ElLoading.service({
target: document.querySelector('.your-button-container'), // 指定容器
text: '加载中...',
})

setTimeout(() => {
loadingInstance.close()
}, 2000)
}


服务方式的好处是不用管指令注册的问题,哪里需要点哪里。
点赞
2026-03-14 13:07