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


    先看效果:

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

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

    开关组件源码:

    1. <template>
    2. <div class="custom-switch" @click="switchClick">
    3. <div style="width: fit-content;height: fit-content;" v-loading="loading">
    4. <el-switch style="position: relative;" v-bind="$attrs">el-switch>
    5. div>
    6. div>
    7. template>
    8. <script>
    9. /**
    10. * el-switch开关组件二次封装
    11. *
    12. * description:
    13. * 移除了el-switch的change事件
    14. * 添加了loading效果
    15. * 开关的value值交给父组件处理
    16. */
    17. export default {
    18. name: 'CustomSwitch',
    19. props: {
    20. loading: {
    21. default: false,
    22. type: Boolean
    23. }
    24. },
    25. data() {
    26. return {}
    27. },
    28. created() {},
    29. mounted() {},
    30. methods: {
    31. switchClick() {
    32. // 如果禁用和loading状态,不emit给父组件
    33. if (this.$attrs.disabled || this.loading) {
    34. return
    35. }
    36. this.$emit('switch-click', this.$attrs.value)
    37. }
    38. }
    39. }
    40. script>
    41. <style lang="scss" scoped>
    42. .custom-switch {
    43. width: 100%;
    44. height: 100%;
    45. display: flex;
    46. align-items: center;
    47. justify-content: center;
    48. ::v-deep .el-loading-mask {
    49. width: 100%;
    50. height: 100%;
    51. border-radius: 10px;
    52. top: 2px;
    53. .el-loading-spinner {
    54. position: relative;
    55. width: 100%;
    56. height: 100%;
    57. top: unset;
    58. margin-top: unset;
    59. display: flex;
    60. align-items: center;
    61. justify-content: center;
    62. svg {
    63. width: 20px;
    64. height: 20px;
    65. }
    66. }
    67. }
    68. }
    69. style>

    父组件:

    1. <template>
    2. <custom-switch
    3. v-model="switchValue"
    4. :loading="switchLoading"
    5. :active-value="1"
    6. :inactive-value="0"
    7. :disabled="switchDisabled"
    8. @switch-click="switchClick"
    9. />
    10. template>
    1. <script>
    2. import CustomSwitch from './custom-switch.vue'
    3. export default {
    4. components: { CustomSwitch },
    5. data() {
    6. return {
    7. switchValue: 1,
    8. switchLoading: false,
    9. switchDisabled: false
    10. }
    11. },
    12. methods: {
    13. switchClick() {
    14. this.switchLoading = true
    15. // 这里就可以调用接口,接口成功后修改值和loading状态
    16. setTimeout(() => {
    17. this.switchValue = !this.switchValue ? 1 : 0
    18. this.switchLoading = false
    19. }, 2000)
    20. }
    21. }
    22. }
    23. script>

  • 相关阅读:
    数据结构与算法--贪心算法
    开源照片管理服务LibrePhotos
    如何查看 Windows 服务器中的登录事件
    iOS 关于UIWebView常见使用方法
    Flink 物理执行图
    【HarmonyOS】低代码平台组件拖拽使用技巧之常用基础组件(下)
    中关村e谷十周年特刊——请回答,2012
    堆排序——向下调整
    Kubernetes入门到精通-Operator 模式
    抖音自媒体运营的5个技巧,让你的账号快速涨粉
  • 原文地址:https://blog.csdn.net/u011295864/article/details/132766860