解决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
    }
}
相关推荐
指尖时光.11 小时前
Three.js 超全入门综合案例
开发语言·javascript·ecmascript
唐青枫11 小时前
http-server:别再双击 index.html,一条命令把目录变成网站
前端·javascript
学习星球14 小时前
Solid.js 实战:拆解官方 RealWorld 项目
开发语言·javascript·vue.js
YuJie16 小时前
JSBridge 基础知识
前端·javascript
默_笙16 小时前
🍕 后端接口还没写好,前端已经跑起来了?Mock 数据 + axios 接口层,前后端再也不互相"等"
前端·javascript
爱勇宝16 小时前
客户只想看个页面,我却做了一个静态演示发布系统
前端·javascript·后端
界面开发小八哥19 小时前
界面控件DevExpress Blazor v26.1新版亮点 - Navigation(导航)
javascript·.net·界面控件·blazor·devexpress·ui开发
aXin_ya20 小时前
ElementUI (01):Vue2 项目引入 ElementUI使用
elementui·vue
SendTomo20 小时前
send.wang(私传网)基于网页P2P直连传输大文件的优势
javascript·网络·webrtc·html5·p2p
学习星球21 小时前
Astro 全栈实战:拆解 RealWorld 项目
前端·javascript·架构·系统架构·前端框架·c5全栈