以下是一个简单的 loading 自定义指令的示例:

<template>
  <button v-loading="isLoading" @click="fetchData">Fetch Data</button>
</template>

<script>
  import { ref } from 'vue';

  export default {
    setup() {
      const isLoading = ref(false);

      const fetchData = async () => {
        isLoading.value = true;
        // do something async
        isLoading.value = false;
      };

      return {
        isLoading,
        fetchData,
      };
    },
    directives: {
      loading: {
        mounted(el, binding) {
          const spinner = document.createElement('span');
          spinner.className = 'spinner'; // add spinner class
          el.appendChild(spinner); // add spinner element to the button

          if (binding.value) {
            el.disabled = true; // disable the button
            el.classList.add('loading'); // add loading class
          }
        },
        updated(el, binding) {
          if (binding.value !== binding.oldValue) {
            el.disabled = binding.value;
            el.classList[binding.value ? 'add' : 'remove']('loading');
          }
        },
      },
    },
  };
</script>

<style>
  .spinner {
    display: inline-block;
    border: 2px solid #fff;
    border-top-color: #333;
    border-radius: 50%;
    width: 1em;
    height: 1em;
    animation: spin 0.6s linear infinite;
    margin-right: 0.5rem;
  }

  .loading {
    opacity: 0.6;
    cursor: not-allowed;
  }

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }
</style>

在上述代码中,我们创建了一个名为 loading 的自定义指令。当 v-loading 绑定的值为 true 时,指令会向按钮添加一个带有旋转动画的圆形加载动画,并禁用按钮。当 v-loading 绑定的值为 false 时,指令会移除加载动画并启用按钮。

mountedupdated 钩子函数中,我们通过 el 参数获取到按钮元素,并在其上添加或移除加载动画、禁用状态等。我们还创建了一个 isLoading 变量来保存加载状态,并在 fetchData 函数中修改它的值。

最后,我们在模板中使用 v-loading 指令来绑定加载状态,并在点击按钮时触发 fetchData 函数

vue3写一个loading的自定义指令

原文地址: https://www.cveoy.top/t/topic/fbU9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录