解决Element-Plus中el-switch的change方法自动触发问题

下面el-switch代码片段是在el-table里使用

html 复制代码
<el-switch 
    v-else-if="col.prop == 'status'" 
    v-model="scope.row.status" 
    :active-value="'0'" 
    :inactive-value="'1'" 
    :before-change="beforeStatus" 
    @change="changStatus(scope.row.status, scope.row.goodsId)">
</el-switch>

el-switch方法代码是Vue3.0框架 typeScript语法格式

javascript 复制代码
<script setup lang="ts">
// 该引入是全局封装getCurrentInstance()方法 代码在下面
import comInstance from "@/hooks/comInstance";

// 获取全局属性
const { global } = comInstance();

// 判断是否在点击弹窗确认按钮时才调用接口
const tags = ref('')

// before方法加一个弹窗提示是否操作
const beforeStatus = async () => {
    const confirm = await global.$confirm('确定操作吗?');
    return new Promise((resolve, reject) => {
        if (confirm) {
            // 点击确认按钮时设置tags值
            tags.value = 'confirmStatus'
            return resolve(confirm)
        } else {
            return reject(confirm)
        }
    })
}

const changStatus = async (type: string, goodsId: string) => {
    // 判断tags值 这样就不会进页面时调用了
    if (tags.value == 'confirmStatus') {
        const res = await upAndDownApi({
            goodsId: goodsId,
            status: type
        }).catch(() => { })
        if (res && res.code == 200) {
            // 刷新表格
            getGoodsList()
        }
    }
}
</script>

@/hooks/comInstance代码 全局封装getCurrentInstance()方法

getCurrentInstance()方法是Vue3 Composition API中的一个API函数。它的作用是返回一个组件实例对象,可以用来操作当前组件的各种属性和方法。这个方法是一个全局API,可以在任何地方使用。

javascript 复制代码
import { getCurrentInstance, ComponentInternalInstance } from "vue";

// 获取挂载属性
export default function useInstance() {
    const { appContext, proxy } = getCurrentInstance() as ComponentInternalInstance
    const global = appContext.config.globalProperties;
    return {
        proxy,
        global
    }
}
相关推荐
多看书少吃饭21 小时前
Vue + Java + Python 打造企业级 AI 知识库与任务分发系统(RAG架构全解析)
java·vue.js·笔记
~无忧花开~1 天前
React生命周期全解析
开发语言·前端·javascript·react.js·前端框架·react
哈__1 天前
ReactNative项目OpenHarmony三方库集成实战:react-native-maps
javascript·react native·react.js
SuperEugene1 天前
Axios + Vue 错误处理规范:中后台项目实战,统一捕获系统 / 业务 / 接口异常|API 与异步请求规范篇
前端·javascript·vue.js·前端框架·axios
行走的陀螺仪1 天前
手写 Vue3 极简 i18n
前端·javascript·vue.js·国际化·i18n
羽沢311 天前
一篇简单的STOMP教程QAQ
前端·javascript·stomp
加个鸡腿儿1 天前
从"包裹器"到"确认按钮"——一个组件的三次重构
前端·vue.js·设计模式
Kel1 天前
深入 OpenAI Node SDK:一个请求的奇幻漂流
javascript·人工智能·架构
子兮曰1 天前
AI写代码坑了90%程序员!这5个致命bug,上线就炸(附避坑清单)
前端·javascript·后端
BUG胡汉三1 天前
自建在线文档编辑服务:基于 Collabora CODE + Spring Boot + Vue 3 的完整实现
vue.js·spring boot·后端·在线编辑