element-ui switch开关组件二次封装,添加loading效果,点击时调用接口后改变状态

先看效果:

element-ui中的switch开关无loading属性(在element-plus时加入了),而且点击时开关状态就会切换,这使得在需要调用接口后再改变开关状态变得比较麻烦。

思路:switch开关外包一层div,给div添加click事件,emit给父组件,在父组件里进行开关状态的切换。

开关组件源码:

html 复制代码
<template>
  <div class="custom-switch" @click="switchClick">
    <div style="width: fit-content;height: fit-content;" v-loading="loading">
      <el-switch style="position: relative;" v-bind="$attrs"></el-switch>
    </div>
  </div>
</template>

<script>
/**
 * el-switch开关组件二次封装
 * 
 * description:
 * 移除了el-switch的change事件
 * 添加了loading效果
 * 开关的value值交给父组件处理
 */
export default {
  name: 'CustomSwitch',
  props: {
    loading: {
      default: false,
      type: Boolean
    }
  },
  data() {
    return {}
  },
  created() {},
  mounted() {},
  methods: {
    switchClick() {
      // 如果禁用和loading状态,不emit给父组件
      if (this.$attrs.disabled || this.loading) {
        return
      }
      this.$emit('switch-click', this.$attrs.value)
    }
  }
}
</script>
<style lang="scss" scoped>
.custom-switch {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  ::v-deep .el-loading-mask {
    width: 100%;
    height: 100%;
    border-radius: 10px;
    top: 2px;
    .el-loading-spinner {
      position: relative;
      width: 100%;
      height: 100%;
      top: unset;
      margin-top: unset;
      display: flex;
      align-items: center;
      justify-content: center;
      svg {
        width: 20px;
        height: 20px;
      }
    }
  }
}
</style>

父组件:

html 复制代码
<template>
    <custom-switch
        v-model="switchValue"
        :loading="switchLoading"
        :active-value="1"
        :inactive-value="0"
        :disabled="switchDisabled"
        @switch-click="switchClick"
    />
</template>
html 复制代码
<script>
import CustomSwitch from './custom-switch.vue'

export default {
    components: { CustomSwitch },
    data() {
        return {
            switchValue: 1,
            switchLoading: false,
            switchDisabled: false
        }
    },
    methods: {
        switchClick() {
            this.switchLoading = true
            // 这里就可以调用接口,接口成功后修改值和loading状态
            setTimeout(() => {
                this.switchValue = !this.switchValue ? 1 : 0
                this.switchLoading = false
            }, 2000)
        }
    }
}
</script>
相关推荐
TT哇1 小时前
【实习 】银行经理端两个核心功能的开发与修复(银行经理绑定逻辑修复和线下领取扫码功能开发)
java·vue.js
星光不问赶路人3 小时前
vue3使用jsx语法详解
前端·vue.js
weixin79893765432...3 小时前
Vue 组件的更新过程(编译系统 + 响应式系统 + 虚拟 DOM & Diff)
vue.js
我是伪码农4 小时前
Vue 智慧商城项目
前端·javascript·vue.js
小书包酱5 小时前
在 VS Code中,vue2-vuex 使用终于有体验感增强的插件了。
vue.js·vuex
Zhencode5 小时前
Vue3 响应式依赖收集与更新之effect
前端·vue.js
天下代码客6 小时前
使用electronc框架调用dll动态链接库流程和避坑
前端·javascript·vue.js·electron·node.js
weixin79893765432...7 小时前
Vue 渲染体系“三件套”(template 模板语法、h 函数和 JSX 语法)
vue.js·h函数·template 模板·jsx 语法
xkxnq7 小时前
第五阶段:Vue3核心深度深挖(第74天)(Vue3计算属性进阶)
前端·javascript·vue.js
Hilaku7 小时前
不要在简历上写精通 Vue3?来自面试官的真实劝退
前端·javascript·vue.js