Vue 3 自定义指令实现 Loading 效果
<template>
<div>
<button v-loading='loading' @click='handleClick'>Click me</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const loading = ref(false);
const handleClick = () => {
loading.value = true;
setTimeout(() => {
loading.value = false;
}, 2000);
};
return {
loading,
handleClick,
};
},
directives: {
loading: {
mounted(el, binding) {
const div = document.createElement('div');
div.innerHTML = `
<div class='loading-mask' style='position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 9999; background-color: rgba(0, 0, 0, 0.5);'>
<div class='loading-icon' style='position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #fff;'>
<i class='el-icon-loading'></i>
<span>loading</span>
</div>
</div>
`;
el.appendChild(div);
if (binding.value) {
el.style.position = 'relative';
el.style.overflow = 'hidden';
div.style.display = 'flex';
} else {
el.style.position = '';
el.style.overflow = '';
div.style.display = 'none';
}
},
updated(el, binding) {
const div = el.querySelector('.loading-mask');
if (binding.value) {
el.style.position = 'relative';
el.style.overflow = 'hidden';
div.style.display = 'flex';
} else {
el.style.position = '';
el.style.overflow = '';
div.style.display = 'none';
}
},
},
},
};
</script>
<p>在这个示例中,我们使用了 Vue 3 的 Composition API,创建了一个 <code>loading</code> 变量和一个 <code>handleClick</code> 函数,并将它们暴露给模板使用。当用户点击按钮时,<code>loading</code> 变量会被设置为 <code>true</code>,在 2 秒后再设置为 <code>false</code>,以模拟一个异步加载的过程。</p>
<p>我们还定义了一个 <code>loading</code> 自定义指令,它会在指令绑定的元素上添加一个 loading 效果。在 <code>mounted</code> 钩子函数中,我们创建了一个 loading 的 HTML 结构并添加到元素中,并根据指令的值来显示或隐藏这个 loading。在 <code>updated</code> 钩子函数中,我们也要根据指令的值来更新 loading 的显示状态。</p>
<p>在模板中,我们使用 <code>v-loading</code> 指令来绑定 loading 的状态,并在按钮上添加一个点击事件。当 <code>loading</code> 的值为 <code>true</code> 时,按钮会被禁用并显示 loading 效果,当 <code>loading</code> 的值为 <code>false</code> 时,按钮会恢复可用状态。</p>
原文地址: https://www.cveoy.top/t/topic/n4ag 著作权归作者所有。请勿转载和采集!