解决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
    }
}
相关推荐
GISer_Jing14 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩14 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
油炸自行车14 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
丷丩18 小时前
MapLibre GL JS第19课:实时更新要素
前端·javascript·gis·map·mapbox·maplibre gl js
xiaohua0708day19 小时前
Lodash库
前端·javascript·vue.js
万物皆对象66619 小时前
切换路由时页面空白问题(vue3)
前端·vue.js·typescript
突然好热19 小时前
TS 调试技巧
前端·javascript·typescript
h64648564h19 小时前
Flutter 国际化(i18n)全指南:一键切换中/英/日多语言
前端·javascript·flutter
丷丩21 小时前
MapLibre GL JS第8课:禁用滚动缩放
javascript·mapbox·maplibre gl js
李剑一21 小时前
小红书前端架构面试问的挺深入啊!面试官:Vue中组合式API与选项式API的设计权衡
vue.js·面试