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>
相关推荐
PBitW几秒前
工作中突然发现零宽字符串的作用了!
前端·javascript·vue.js
工业互联网专业10 分钟前
基于springboot+vue的校园二手物品交易平台
java·vue.js·spring boot·毕业设计·源码·课程设计·校园二手物品交易平台
冷冷清清中的风风火火26 分钟前
关于敏感文件或备份 安全配置错误 禁止通过 URL 访问 Vue 项目打包后的 .gz 压缩文件
前端·vue.js·安全
城南已开9791 小时前
vue部署到nginx服务器 启用gzip
服务器·vue.js·nginx
RePeaT1 小时前
高亮自定义指令,表格前一列也高亮?
前端·vue.js·笔记
前端大卫1 小时前
Vue 3 调用深层组件方法,这 3 招够用了!
前端·vue.js
tryCbest2 小时前
Vue2集成ElementUI实现左侧菜单导航
前端·javascript·elementui
唐璜Taro2 小时前
Vue的模板编译过程
前端·javascript·vue.js
AlexJee2 小时前
el-scrollbar搭配el-backtop滚动到最顶/最底 & el-scrollbar在focus时出现黑框的解决办法
vue.js
柚子a2 小时前
element-plus el-upload 因默认自动上传导致的一系列问题
vue.js·element