Vue中指令directive(内置指令+自定义指令)的使用和实例

一、 内置指令一览以及说明:

1、v-bind:响应并更新DOM特性;例如:v-bind:href  v-bind:class  v-bind:title  v-bind:bb
2、v-on:用于监听DOM事件; 例如:v-on:click  v-on:keyup
3、v-model:数据双向绑定;用于表单输入等;例如:<input v-model="message">
4、v-show:条件渲染指令,为DOM设置css的style属性
5、v-if:条件渲染指令,动态在DOM内添加或删除DOM元素
6、v-else:条件渲染指令,必须跟v-if成对使用
7、v-for:循环指令;例如:<li v-for="(item,index) in todos"></li>
8、v-else-if:判断多层条件,必须跟v-if成对使用;
9、v-text:更新元素的textContent;例如:<span v-text="msg"></span> 等同于 <span>{{msg}}</span>10、v-html:更新元素的innerHTML;
11、v-pre:不需要表达式,跳过这个元素以及子元素的编译过程,以此来加快整个项目的编译速度;例如:<span v-pre>{{ this will not be compiled }}</span>12、v-cloak:不需要表达式,防止页面加载时出现闪烁问题( 解决插值表达式的闪烁问题 
		如:Js脚本加载慢, 引发页面先出现{{name}},再渲染成真实效果的情况
13、v-once:不需要表达式,只渲染元素或组件一次,随后的渲染,组件/元素以及下面的子元素都当成静态页面不在渲染。

1 .v-cloak实例

<html>
	 <style type="text/css">
  /* 
    1、通过属性选择器 选择到 带有属性 v-cloak的标签  让他隐藏
 */
  [v-cloak]{
    /* 元素隐藏    */
    display: none;
  }
  </style>
<body>
  <div id="app">
    <!-- 让带有插值 语法的   添加 v-cloak 属性 
         在 数据渲染完成之后,v-cloak 属性会被自动去除,
         v-cloak一旦移除也就是没有这个属性了  属性选择器就选择不到该标签
		 也就是对应的标签会变为可见
    -->
    <div v-cloak  >{{msg}}</div>
  </div>
  <!-- 
  	假如这里引入的vue.js耗时5秒钟以上,那么页面先出现{{msg}}, 5秒后显示 “Hello Vue”
  	这样用户体验太差,使用v-cloak配合<style>中display: none可以解决,
  	5秒钟之前啥都不显示,5秒中之后Js加载完成,页面直接出现 “Hello Vue”
  -->
  <script type="text/javascript" src="js/vue.js"></script>//引入vue.js文件
  <script type="text/javascript">
    var vm = new Vue({
      //  el   指定元素 id 是 app 的元素  
      el: '#app',
      //  data  里面存储的是数据
      data: {
        msg: 'Hello Vue'
      }
    });
	</script>
</body>
</html>

二、Vue中自定义指令directive的使用和实例

注:

  • Vue中自定义指令, 定义时不加v-,但使用时要加v- ;

  • Vue中指令名如果是多个单词,要使用kebab-case命名方式
    [如:text-big,使用时: v-text-big], 不要用camelCase命名

  • Vue中自定义指令分为全局注册和局部注册,如下:

1. 自定义指令局部注册-实例参考

<!-- ====================== 局部指令注册使用,如下实例参考:====================== --> 
<template>
  <div>
    <div class="study-directive" v-color='fontColor'>自定义指令总结:可以是变量
      <!-- <div class="study-directive" v-color='"blue"'>自定义指令总结:可以是字符串 -->
      <br />
      <div v-colors='fontColors'>注册多个自定义指令</div>
      <button @click="changeColor">改变颜色</button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      fontColor: "red",
      fontColors: "green"
    };
  },
// 注册一个局部指令 v-color
  directives: {
    color: {
      //被绑定元素插入父节点时调用(执行一次)
      inserted: function(el, bind) {
        el.style.color = bind.value;
      },
      //组件值更新时
      update: function(el, bind) {
        //当我们触发 changeColor 修改颜色值时,然而视图并没有更新,因为指令也存在生命周期 ,
        //所以如果需要视图更新,使用更新阶段
        el.style.color = bind.value;
      }
    },
    //存在多个指令时:
    colors: {
      inserted: function(el, bind) {
        el.style.color = bind.value;
      },
      update: function(el, bind) {
        el.style.color = bind.value;
      }
    }
  },
  methods: {
    changeColor() {
      this.fontColor = "green";
    }
  }
};
</script>
<style scoped>
.study-directive {
  margin: 200px 200px 10px;
  background: gray;
  padding: 40px;
  width: 500px;
  font-size: 18px;
}
</style>

2. 自定义指令全局注册-实例参考

// ======================全局注册实例如下参考: ====================
// 在mian.js中
Vue.directive('color', {
  inserted: function (el, bind) {
    el.style.color = bind.value
  }
})

//  全局注册多个自定义指令: -->
//  	1. 创建directive.js文件,然后编写全局的自定义组件; 
export default (Vue) => {
    Vue.directive('color', {
        inserted: function (el, bind) {
            el.style.color = bind.value
        },
        update: function (el, bind) {
            el.style.color = bind.value;
        }
    })
    Vue.directive('colors', {
        inserted: function (el, bind) {
            el.style.color = bind.value
        }
    })
}

//  	2. 在main.js文件中引入directive.js文件,然后使用Vue.use(directive)调用;
import directive from "@/utils/directives.js";
Vue.use(directive)

//  	3. 在需要使用的地方直接使用 
 <div v-color='"red"'> v-color颜色自定义指令的测试实例</div>

3. 自定义指令-函数式声明

<!-- 
	本实例自定义指令名为:word ,使用时:v-word;
	v-word功能: 和v-text功能类似,但会把绑定的数值放大10倍。
-->
    <div class="root">
        <h1 v-text="n"></h1>
        <h1 v-word="n"></h1>
    </div>

    <script>
        Vue.config.productionTip = false
        new Vue({
            el: '.root',
            data: {
                n: '10'
            },
            directives: {
            	// 这里使用函数式的声明方式
                word(element, binding) {
                    element.innerText = binding.value * 10
                }
            }
        })
    </script>

4. 自定义指令-对象式声明 [含钩子函数 详解 ]

// ==================== 钩子函数使用说明 ============================
// bind: 只调用一次,指令第一次绑定到元素时调用,可以定义一个在绑定时执行一次的初始化动作。
// inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。
// update: 被绑定元素所在的模板更新时调用,而不论绑定值是否变化。通过比较更新前后的绑定值。
// componentUpdated: 被绑定元素所在模板完成一次更新周期时调用。
// unbind: 只调用一次, 指令与元素解绑时调用。
/**
 * 自定义指令对应每个钩子函数的 功能详解
 */
import Vue from 'vue'

/**
 * 模板
 * v-lang
 * 五个注册指令的钩子函数
 */
Vue.directive('lang', {
  /**
   * 1.被绑定 , 做绑定的准备工作
   * 比如添加事件监听器,或是其他只需要执行一次的复杂操作
   */
  bind: function(el, binding, vnode) {
    console.log('1 - bind');
  },
  // 2.绑定到节点,页面产生该Dom元素了
  inserted: function(el, binding, vnode) {
    console.log('2 - inserted');
  },
  /**
   * 3.组件更新 , 根据获得的新值执行对应的更新 , 对于初始值也会调用一次
   */
  update: function(el, binding, vnode, oldVnode) {
    console.log('3 - update');
  },
  // 4.组件更新完成
  componentUpdated: function(el, binding, vnode, oldVnode) {
    console.log('4 - componentUpdated');
  },
  /**
   * 5.解绑 ,做清理操作 , 比如移除bind时绑定的事件监听器
   */
  unbind: function(el, binding, vnode) {
    console.log('5 - bind');
  }
})
/**
钩子函数
1、bind:只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个绑定时执行一次的初始化动作。
2、inserted:被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于document中)。
3、update:被绑定于元素所在的模板更新时调用,而无论绑定值是否变化。通过比较更新前后的绑定值,可以忽略不必要的模板更新。
4、componentUpdated:被绑定元素所在模板完成一次更新周期时调用。
5、unbind:只调用一次,指令与元素解绑时调用。
*/

/**
钩子函数的参数:(el, binding, vnode, oldVnode)
el:指令所绑定的元素,可以用来直接操作 DOM 。
binding:一个对象,包含以下属性
  name:指令名,不包含v-的前缀;
  value:指令的绑定值;例如:v-my-directive="1+1",value的值是2;
  oldValue:指令绑定的前一个值,仅在update和componentUpdated钩子函数中可用,无论值是否改变都可用;
  expression:绑定值的字符串形式;例如:v-my-directive="1+1",expression的值是'1+1';
  arg:传给指令的参数;例如:v-my-directive:foo,arg的值为 'foo';
  modifiers:一个包含修饰符的对象;例如:v-my-directive.a.b,modifiers的值为{'a':true,'b':true}
vnode:Vue编译的生成虚拟节点;
oldVnode:上一次的虚拟节点,仅在update和componentUpdated钩子函数中可用。
*/
<!--     v-fbingd实例参考:   
	本实例自定义指令名为:fbind ,使用时:v-fbind;
	v-fbind:和v-bind功能类似,但可以让其绑定的input元素默认获取焦点。
-->
    <input type="text" v-bind:value="n">
    <input type="text" v-fbind:value="n">
    
    <script>
        Vue.config.productionTip = false
        new Vue({
            el: '.root',
            data: {
                n: '10'
            },
            directives: {
            	// 对象式声明 ,本例通过inserted和updaet两个钩子函数即可实现
                fbind: {
                    bind: function(el, binding, vnode) {
					   console.log('1 - bind');
					  },
					  inserted: function(el, binding, vnode) {
					    console.log('2 - inserted');
					    el.innertext = binding.value
					    element.focus()
					  },
					  update: function(el, binding, vnode, oldVnode) {
					    console.log('3 - update');
					    el.innertext = binding.value
					    element.focus()
					  },
					  componentUpdated: function(el, binding, vnode, oldVnode) {
					    console.log('4 - componentUpdated');
					  },
					  unbind: function(el, binding, vnode) {
					    console.log('5 - bind');
					  }
                }
            }
        })
    </script>

5. 常用的8个自定义指令合集

//  ================ 8个常用的自定义指令 =======================================
	复制粘贴指令 v-copy
	长按指令 v-longpress
	输入框防抖指令 v-debounce
	禁止表情及特殊字符 v-emoji
	图片懒加载 v-LazyLoad
	权限校验指令 v-premission
	实现页面水印 v-waterMarker
	拖拽指令 v-draggable
//  ================ 8个常用的自定义指令 =======================================

5-1 批量注册指令,新建 directives/index.js 文件

import copy from './copy'
import longpress from './longpress'
// 自定义指令
const directives = {
  copy,
  longpress,
}

export default {
  install(Vue) {
    Object.keys(directives).forEach((key) => {
      Vue.directive(key, directives[key])
    })
  },
}

5-2 在 main.js 引入并调用

import Vue from 'vue'
import Directives from './JS/directives'
Vue.use(Directives)

5-3 各自定义指令的代码及详解

5-3-1 v-copy: 实现一键复制文本内容,用于鼠标右键粘贴
// v-copy指令的定义
const copy = {
  bind(el, { value }) {
    el.$value = value
    el.handler = () => {
      if (!el.$value) {
        // 值为空的时候,给出提示。可根据项目UI仔细设计
        console.log('无复制内容')
        return
      }
      // 动态创建 textarea 标签
      const textarea = document.createElement('textarea')
      // 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘,同时将 textarea 移出可视区域
      textarea.readOnly = 'readonly'
      textarea.style.position = 'absolute'
      textarea.style.left = '-9999px'
      // 将要 copy 的值赋给 textarea 标签的 value 属性
      textarea.value = el.$value
      // 将 textarea 插入到 body 中
      document.body.appendChild(textarea)
      // 选中值并复制
      textarea.select()
      const result = document.execCommand('Copy')
      if (result) {
        console.log('复制成功') // 可根据项目UI仔细设计
      }
      document.body.removeChild(textarea)
    }
    // 绑定点击事件,就是所谓的一键 copy 啦
    el.addEventListener('click', el.handler)
  },
  // 当传进来的值更新的时候触发
  componentUpdated(el, { value }) {
    el.$value = value
  },
  // 指令与元素解绑的时候,移除事件绑定
  unbind(el) {
    el.removeEventListener('click', el.handler)
  },
}
export default copy
<!-- v-copy 使用实例 -->
<template>
  <button v-copy="copyText">复制</button>
</template>
 
<script> export default {
    data() {
      return {
        copyText: 'a copy directives',
      }
    },
  } </script>
5-3-2 v-longpress: 实现长按,用户需要按下并按住按钮几秒钟,触发相应的事件
const longpress = {
  bind: function (el, binding, vNode) {
    if (typeof binding.value !== 'function') {
      throw 'callback must be a function'
    }
    // 定义变量
    let pressTimer = null
    // 创建计时器( 2秒后执行函数 )
    let start = (e) => {
      if (e.type === 'click' && e.button !== 0) {
        return
      }
      if (pressTimer === null) {
        pressTimer = setTimeout(() => {
          handler()
        }, 2000)
      }
    }
    // 取消计时器
    let cancel = (e) => {
      if (pressTimer !== null) {
        clearTimeout(pressTimer)
        pressTimer = null
      }
    }
    // 运行函数
    const handler = (e) => {
      binding.value(e)
    }
    // 添加事件监听器
    el.addEventListener('mousedown', start)
    el.addEventListener('touchstart', start)
    // 取消计时器
    el.addEventListener('click', cancel)
    el.addEventListener('mouseout', cancel)
    el.addEventListener('touchend', cancel)
    el.addEventListener('touchcancel', cancel)
  },
  // 当传进来的值更新的时候触发
  componentUpdated(el, { value }) {
    el.$value = value
  },
  // 指令与元素解绑的时候,移除事件绑定
  unbind(el) {
    el.removeEventListener('click', el.handler)
  },
}
 
export default longpress
<!-- 使用实例 -->
<template>
  <button v-longpress="longpress">长按</button>
</template>
 
<script> export default {
  methods: {
    longpress () {
      alert('长按指令生效')
    }
  }
} </script>
5-3-3 v-debounce: 防抖指令,如防止按钮在短时间内被多次点击
const debounce = {
  inserted: function (el, binding) {
    let timer
    el.addEventListener('keyup', () => {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        binding.value()
      }, 1000)
    })
  },
}
 
export default debounce
<template>
  <button v-debounce="debounceClick">防抖</button>
</template>
 
<script> export default {
  methods: {
    debounceClick () {
      console.log('短时间内只触发一次')
    }
  }
} </script>
5-3-4 v-emoji: 限制不能输入表情和特殊字符,只能输入数字或字母
let findEle = (parent, type) => {
  return parent.tagName.toLowerCase() === type ? parent : parent.querySelector(type)
}
 
const trigger = (el, type) => {
  const e = document.createEvent('HTMLEvents')
  e.initEvent(type, true, true)
  el.dispatchEvent(e)
}
 
const emoji = {
  bind: function (el, binding, vnode) {
    // 正则规则可根据需求自定义
    var regRule = /[^u4E00-u9FA5|d|a-zA-Z|rns,.?!,。?!…—&$=()-+/*{}[]]|s/g
    let $inp = findEle(el, 'input')
    el.$inp = $inp
    $inp.handle = function () {
      let val = $inp.value
      $inp.value = val.replace(regRule, '')
 
      trigger($inp, 'input')
    }
    $inp.addEventListener('keyup', $inp.handle)
  },
  unbind: function (el) {
    el.$inp.removeEventListener('keyup', el.$inp.handle)
  },
}
 
export default emoji
<template>
  <input type="text" v-model="note" v-emoji />
</template>
5-3-5 v-LazyLoad: 懒加载指令,如:只加载浏览器可见区域的图片,提高页面加载速度
const LazyLoad = {
  // install方法
  install(Vue, options) {
    const defaultSrc = options.default
    Vue.directive('lazy', {
      bind(el, binding) {
        LazyLoad.init(el, binding.value, defaultSrc)
      },
      inserted(el) {
        if (IntersectionObserver) {
          LazyLoad.observe(el)
        } else {
          LazyLoad.listenerScroll(el)
        }
      },
    })
  },
  // 初始化
  init(el, val, def) {
    el.setAttribute('data-src', val)
    el.setAttribute('src', def)
  },
  // 利用IntersectionObserver监听el
  observe(el) {
    var io = new IntersectionObserver((entries) => {
      const realSrc = el.dataset.src
      if (entries[0].isIntersecting) {
        if (realSrc) {
          el.src = realSrc
          el.removeAttribute('data-src')
        }
      }
    })
    io.observe(el)
  },
  // 监听scroll事件
  listenerScroll(el) {
    const handler = LazyLoad.throttle(LazyLoad.load, 300)
    LazyLoad.load(el)
    window.addEventListener('scroll', () => {
      handler(el)
    })
  },
  // 加载真实图片
  load(el) {
    const windowHeight = document.documentElement.clientHeight
    const elTop = el.getBoundingClientRect().top
    const elBtm = el.getBoundingClientRect().bottom
    const realSrc = el.dataset.src
    if (elTop - windowHeight < 0 && elBtm > 0) {
      if (realSrc) {
        el.src = realSrc
        el.removeAttribute('data-src')
      }
    }
  },
  // 节流
  throttle(fn, delay) {
    let timer
    let prevTime
    return function (...args) {
      const currTime = Date.now()
      const context = this
      if (!prevTime) prevTime = currTime
      clearTimeout(timer)
 
      if (currTime - prevTime > delay) {
        prevTime = currTime
        fn.apply(context, args)
        clearTimeout(timer)
        return
      }
 
      timer = setTimeout(function () {
        prevTime = Date.now()
        timer = null
        fn.apply(context, args)
      }, delay)
    }
  },
}
 
export default LazyLoad
<img v-LazyLoad="xxx.jpg" />
5-3-6 v-permission: 自定义权限指令,对需要权限判断的 Dom 进行显示隐藏
function checkArray(key) {
  let arr = ['1', '2', '3', '4']
  let index = arr.indexOf(key)
  if (index > -1) {
    return true // 有权限
  } else {
    return false // 无权限
  }
}
 
const permission = {
  inserted: function (el, binding) {
    let permission = binding.value // 获取到 v-permission的值
    if (permission) {
      let hasPermission = checkArray(permission)
      if (!hasPermission) {
        // 没有权限 移除Dom元素
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  },
}
 
export default permission
<div class="btns">
  <!-- 显示 -->
  <button v-permission="'1'">权限按钮1</button>
  <!-- 不显示 -->
  <button v-permission="'10'">权限按钮2</button>
</div>
5-3-7 v-waterMarker: 给整个页面添加背景水印
function addWaterMarker(str, parentNode, font, textColor) {
  // 水印文字,父元素,字体,文字颜色
  var can = document.createElement('canvas')
  parentNode.appendChild(can)
  can.width = 200
  can.height = 150
  can.style.display = 'none'
  var cans = can.getContext('2d')
  cans.rotate((-20 * Math.PI) / 180)
  cans.font = font || '16px Microsoft JhengHei'
  cans.fillStyle = textColor || 'rgba(180, 180, 180, 0.3)'
  cans.textAlign = 'left'
  cans.textBaseline = 'Middle'
  cans.fillText(str, can.width / 10, can.height / 2)
  parentNode.style.backgroundImage = 'url(' + can.toDataURL('image/png') + ')'
}
 
const waterMarker = {
  bind: function (el, binding) {
    addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor)
  },
}
 
export default waterMarker
<template>
  <div v-waterMarker="{text:'lzg版权所有',textColor:'rgba(180, 180, 180, 0.4)'}"></div>
</template>
5-3-8 v-draggable: 拖拽指令,可在页面可视区域任意拖拽元素
const draggable = {
  inserted: function (el) {
    el.style.cursor = 'move'
    el.onmousedown = function (e) {
      let disx = e.pageX - el.offsetLeft
      let disy = e.pageY - el.offsetTop
      document.onmousemove = function (e) {
        let x = e.pageX - disx
        let y = e.pageY - disy
        let maxX = document.body.clientWidth - parseInt(window.getComputedStyle(el).width)
        let maxY = document.body.clientHeight - parseInt(window.getComputedStyle(el).height)
        if (x < 0) {
          x = 0
        } else if (x > maxX) {
          x = maxX
        }
 
        if (y < 0) {
          y = 0
        } else if (y > maxY) {
          y = maxY
        }
 
        el.style.left = x + 'px'
        el.style.top = y + 'px'
      }
      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null
      }
    }
  },
}
export default draggable
<template>
  <div class="el-dialog" v-draggable></div>
</template>
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值