hello,大家好,这是我的第一篇文章,今天想给大家讲一下怎么用vue指令写一个loading动画话不多说直接上代码了
<div v-loading="isLoading">{{ message }}</div>
<button @click="showLoading">显示loading</button>
data() {
return {
message: "",
isLoading: false
};
},
methods: {
showLoading() {
this.isLoading = true;
setTimeout(() => {
this.message = "数据更新";
this.isLoading = false;
}, 3000);
}
}
这里是模板和方法,下面就是关键了
Vue.directive("loading", {
update(el, binding, vNode) {
if (binding.value) {
const div = document.createElement("div");
div.innerText = "加载中...";
div.setAttribute("id", "loading");
div.style.cssText += `; position: absolute;top:0;left:0;width:100%;height:100%;
background:rgba(0, 0, 0, .7);color:white;display:flex;justifyContent:center;alignItems:center;`;
// 这里解释一下cssText,这个是给元素增加样式,前面的分号是兼容ie9的
document.body.append(div);
} else {
document.body.removeChild(document.querySelector("#loading"));
}
}
});
这里我们要用到的是update这个钩子函数,其余的钩子函数可以在官网看到
update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新 (详细的钩子函数参数见下)
update接收三个参数el,binding,vnode,这里我们主要用到binding这个参数
点击的时候第一次改变指,这时参数会为true,这时我们创建一个元素增加样式、文本内容等,3秒后参数变为false,再次进入到函数里面,这时我们移除这个元素,然后就完成了,是不是很简单呢?
指令的好处就是很方便并且不用每次定义一个元素,还能打包成一个插件直接引用,是不是很方便呢?好了,今天就分享到这里!