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

Zz乐佳 阅读 2

我在用 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>
我来解答 赞 1 收藏
二维码
手机扫码查看
1 条解答
慕容旗施
你的问题大概率是没注册 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