vue2自定义指令

本节目标

  • 快速入门
  • v-loading

快速入门

指令对比

基本语法

  1. 使用: v-指令名="指令值"
  2. 定义: 通过 directives 局部定义或者全局定义
  3. 通过事件对象 el 可以拿到指令所在元素
  4. 通过形参 binding 可以拿到指令的传值
  5. 通过update钩子, 可以监听指令值的变化,进行更新操作

局部注册

复制代码
<template>
  <div id="app">
    <input v-focus type="text" />
  </div>
</template>

<script>
export default {
  // 局部注册自定义指令
  directives: {
    focus: {
      // 指定的生命周期: 指令所在的元素, 挂载完毕后触发
      inserted(el) {
        // el就是指令绑定的元素
        el.focus();
      },
    },
  },
};
</script>

全局注册

复制代码
... ...

Vue.directive('focus', {
  // 指定所在的元素被加载后执行
  inserted: function (el) {
    // el就是所绑定的元素
    el.focus()
  }
})
  
... ...

指令传值

复制代码
<template>
  <div id="app">
    <h2 v-color="color1">我是一个标题</h2>
    <h2 v-color="color2">我是一个标题</h2>
  </div>
</template>

<script>
export default {
  data() {
    return {
      color1: "red",
      color2: "blue",
    }
  },
  // 局部注册自定义指令
  directives: {   
    color: {
      inserted(el, binding) {
        el.style.color = binding.value;
      },
      // 指令的值(binding)修改时触发
      update(el,binding) {
        el.style.color = binding.value;
      }
    }
  },
};
</script>

v-loading

封装一个v-loading指令, 实现加载中的效果

分析

  1. 本质loading效果就是一个蒙层, 盖在盒子上
  2. 数据请求时, 开启loading状态, 添加蒙层
  3. 数据请求完毕, 关闭loading状态, 移除蒙层

实现

  1. 准备一个loading类, 通过伪元素定位, 设置宽高, 实现蒙层

  2. 开启关闭loading状态, 本质只需要添加和移除类名即可

  3. 结合自定义指令的语法进行封装复用

    <template>
    • 我是内容{{ item }}
    </template> <script> export default { data () { return { list: [], isLoading: true, } }, async created () { setTimeout(() => { this.list = [1,2,3,4,5] // 3,关闭loading效果 this.isLoading = false }, 2000) }, directives: { // 1, 注册loading指令 loading: { inserted(el, binding) { binding.value ? el.classList.add('loading') : el.classList.remove('loading') }, update(el, binding) { binding.value? el.classList.add('loading') : el.classList.remove('loading') } } } } </script> <style> /* 伪类 - 蒙层效果 */ .loading:before { content: ''; position: absolute; left: 0; top: 0; width: 100%; height: 100%; background: #fff url('./loading.gif') no-repeat center; }

    .box {
    width: 800px;
    min-height: 500px;
    border: 3px solid orange;
    position: relative;
    }
    </style>

相关推荐
_pengliang12 分钟前
react native ios 2个modal第二个不显示
javascript·react native·react.js
纳兰瑞雪13 分钟前
nodeJs electron程式开发demo
开发语言·前端·javascript
why技术14 分钟前
可怕,看到一个冷血的算法。人心逐利,算法只会更聪明地逐利。
前端·后端·算法
Irene199116 分钟前
Vue 3 中,组合式 API 的 setup() 函数确实先于选项式 API 的生命周期钩子执行
vue.js·执行顺序·组合式 api·选项式 api
计算机学姐29 分钟前
基于SpringBoot的高校体育场馆预约系统【个性化推荐算法+数据可视化统计】
java·vue.js·spring boot·后端·mysql·信息可视化·推荐算法
爱上妖精的尾巴37 分钟前
7-8 WPS JS宏 对象使用实例5--按多字段做多种汇总
javascript·后端·restful·wps·jsa
祎直向前40 分钟前
linuxshell循环,条件分支语句
前端·chrome
LongtengGensSupreme40 分钟前
开放所有跨域 ----前端和后端
前端·后端·ajax·vue·api·jquery
我算哪枝小绿植40 分钟前
react实现日历拖拽效果
前端·react.js·前端框架
白粥44 分钟前
【HTML】文本格式化
前端·javascript·html