2022-04-27 el-switch组件实现beforeChange

今天遇到了一个需求:点击Switch更改音频是否打开,我需要在设置请求响应之后再改变Switch的状态。于是自己把el-switch组件进行了二次封装。

<template>
  <el-switch
    :value="_value"
    @change="onChange"
    v-bind="$attrs"
    :activeValue="activeValue"
    :inactiveValue="inactiveValue"
  >
  </el-switch>
</template>

重新绑定value值,和change事件,其余参数使用attrs传递(attrs 可以收集父组件中的所有传过来的属性除了那些在子组件中通过 props 定义的。

type valueType = string | number | boolean;
type fnType = (arg: valueType) => Promise<boolean>;
props: {
    activeValue: {
      type: [String, Number, Boolean],
      default: true,
    },
    inactiveValue: {
      type: [String, Number, Boolean],
      default: false,
    },
    beforeChange: {
      type: Function as PropType<fnType>,
    },
    value: {
      type: [String, Number, Boolean],
      default: false,
    },
  },

props定义父组件传入的属性

data() {
    return {
      _value: '' as valueType,
    };
  },
  created() {
    this._value = this.value;        // 将父组件传入的value值赋值给子组件
  },
  watch: {
    value: function(v) {
      this._value = v;
    },
  },

监听父组件传入的value值,并赋值给子组件

onChange(changeVal: valueType) {
      // 定义一个变量存储改变之前的值
      let beforeVal: valueType;
      // 保存状态改变之前的值
      if (this.activeValue !== '' && this.inactiveValue !== '') {
        beforeVal =
          changeVal === this.activeValue
            ? this.inactiveValue
            : this.activeValue;
      } else {
        beforeVal = !changeVal;
      }

      if (this.beforeChange != null) {
        // 传入组件changeVal
        this.beforeChange(changeVal)
          .catch(() => {
            changeVal = beforeVal;
          })
          .finally(() => {
            // 请求不管成功还是失败最终会进到这里,成功时changeVal值不变,失败时修改为改变之前的值
            this._value = changeVal;
            this.$emit('change', changeVal);
            // 抛出input事件,修改视图
            this.$emit('input', changeVal);
          });
      }
    },

父组件的beforeChange方法,返回一个Promise,成功状态为修改switch状态,失败则为修改前的状态

setAduioState(state: boolean): Promise<boolean> {
      return new Promise((reslove, reject) => {
        // 定时器设置禁用,防止频繁点击
        setTimeout(() => {
          this.audioDisabled = false;
        }, 2000);
        if (!this.audioDisabled) {
          request
            .serve({
              method: 'post',
              url: '/setAudioSwitch',
              data: qs.stringify({ state: state }),
            })
            .then((res: any) => {
              if (res.errorCode === 200) {
                reslove(true);
              } else {
                // 抛出异常
                throw new Error('设置错误');
              }
            })
            .catch(() => {
              reject(false);
            });
        }
        this.audioDisabled = true;
      });
    },
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容