平湖有做网站得吗,seo长尾关键词,网页开发需求定制,广西茶叶网站建设Vue自定义指令- v-loading封装 文章目录 Vue自定义指令- v-loading封装01-自定义指令自定义指令的两种注册语法#xff1a; 02自定义指令的值03-自定义指令- v-loading指令封装 01-自定义指令 什么是自定义指令#xff1f;
自定义指令#xff1a;自己定义的指令#xff0c…Vue自定义指令- v-loading封装 文章目录 Vue自定义指令- v-loading封装01-自定义指令自定义指令的两种注册语法 02自定义指令的值03-自定义指令- v-loading指令封装 01-自定义指令 什么是自定义指令
自定义指令自己定义的指令可以封装一些dom操作扩展额外功能。
1、例如完成自动聚焦的功能
自定义指令的两种注册语法
全局注册-语法
// 全局注册指令
Vue.directive(focus,{// inserted会在 指令所在的元素被插入到页面中的时候触发inserted (el) {// el 就是我们指令所绑定的元素el.focus()}
})局部注册-语法 // 2.局部注册指令directives: {// 指令名指令配置项focus: {// el 是我么指令所绑定的元素inserted (el) {el.focus()}}}
根据使用场景选择不同的注册方式。 02自定义指令的值
2、例如实现一个color指令 - 传入不同的颜色给标签设置文字颜色
语法
我们再绑定指令的时候可以通过 等号 给我们指令绑定具体的参数。
v-指令名“指令值”绑定指令的值
div v-colorcolor我是内容/div
通过 binding.value可以可以拿到指令值指令值修改会 触发 update 函数
binding.value可以拿到color的值当我们指令被修改后会执行update函数 div classapph1 v-colorcolor1指令的值1/h1h1 v-colorcolor2指令的值2/h1/divscript
export default {data () {return {color1: red,color2: green}},// 注册自定义指令directives: {color: {// 1、inserted 元素被添加到页面时的逻辑inserted (el,binding) {// binding.value 就是指令的值el.style.color binding.value},// 2、update 指令的值修改的时候触发提供dom更新后的逻辑update (el, binding) {el.style.color binding.value}}}
}
/script03-自定义指令- v-loading指令封装 分析 v-loading指令封装
本质 loading 效果就是一个蒙层盖在了盒子上数据请求中开启loading状态添加蒙层数据请求完毕后关闭loading装状态移除蒙层。 实现 准备一个 loading 类通过伪元素定位设置宽高实现蒙层 开启关闭蒙层状态添加移除蒙层本质只需要添加移除类即可 结合自定义指令的语法进行封装 div classbox v-loadingisLoadingscript
// 安装axios yarn add axios
import axios from axios// 接口地址http://hmajax.itheima.net/api/news
// 请求方式get
export default {data () {return {list: [],isLoading: true}},// 定义局部指令directives: {loading: {inserted (el,binding) {// 指令触发后执行当前钩子 insertedbinding.value ? el.classList.add(loading) : el.classList.remove(loading)},update (el,binding) {// 指令值被修改执行当前钩子 updatebinding.value ? el.classList.add(loading) : el.classList.remove(loading)}}},async created () {// 1. 发送请求获取数据const res await axios.get(http://hmajax.itheima.net/api/news)setTimeout(() {// 2. 更新到 list 中用于页面渲染 v-forthis.list res.data.data// 数据响应后改变蒙层状态this.isLoading false}, 2000)}
}
/scriptstyle
.loading:before {content: ;position: absolute;left: 0;top: 0;width: 100%;height: 100%;background: #fff url(./loading.gif) no-repeat center;
}
/style