首頁  >  文章  >  web前端  >  vue中值得了解的4個自訂指令(實用分享)

vue中值得了解的4個自訂指令(實用分享)

青灯夜游
青灯夜游轉載
2021-12-15 19:35:282058瀏覽

除了預設設定的核心指令( v-model 和 v-show ),Vue 也允許註冊自訂指令。本篇文章跟大家分享四個實用的vue自訂指令,希望對大家有幫助。

vue中值得了解的4個自訂指令(實用分享)

四個實用的vue自訂指令

1、#v-drag

需求:滑鼠拖曳元素

想法:

  • 元素偏移量 = 滑鼠滑動後的座標 - 滑鼠初始點選元素時的座標   初始點擊時元素距離視覺區域的top、left。
  • 將可視區域作為邊界,限制在可視區域內拖曳。 【相關推薦:《vue.js教學》】

    #程式碼:

    Vue.directive('drag', {
      inserted(el) {
        let header = el.querySelector('.dialog_header')
        header.style.cssText += ';cursor:move;'
        header.onmousedown = function (e) {
          //获取当前可视区域宽、高
          let clientWidth = document.documentElement.clientWidth
          let clientHeight = document.documentElement.clientHeight
    
          //获取自身宽高
          let elWidth = el.getBoundingClientRect().width
          let elHeight = el.getBoundingClientRect().height
    
          //获取当前距离可视区域的top、left
          let elTop = el.getBoundingClientRect().top
          let elLeft = el.getBoundingClientRect().left
    
          //获取点击时候的坐标
          let startX = e.pageX
          let startY = e.pageY
    
          document.onmousemove = function (e) {
            //元素偏移量 = 鼠标滑动后的坐标 - 鼠标初始点击元素时的坐标 + 初始点击时元素距离可视区域的top、left
            let moveX = e.pageX - startX + elLeft
            let moveY = e.pageY - startY + elTop
    
            //将可视区域作为边界,限制在可视区域里面拖拽
            if ((moveX + elWidth) > clientWidth || moveX < 0 || (moveY + elHeight) > clientHeight || moveY < 0) {
              return
            }
    
            el.style.cssText += &#39;top:&#39; + moveY + &#39;px;left:&#39; + moveX + &#39;px;&#39;
          }
          document.onmouseup = function () {
            document.onmousemove = null
            document.onmouseup = null
          }
        }
      }
    })

    2、v-wordlimit

    需求:後台字段限制了長度,並且區分中英文,中文兩個字節,英文一個字節;所以輸入框需要限制輸入的字數並且區分位元組數,且需回顯已輸入的字數。

    想法:

    • 一個位元組的正則/[\x00-\xff]/g
    • 建立包裹字數限制的元素,並定位佈局在textarea和input框上
    • 分別計算輸入的字元一個位元組的有enLen個,兩個位元組的有cnLen個;用來後面字串截斷處理
    • 當輸入的字數超過限定的字數,截斷處理;substr(0,enLen cnLen)
    • 介面更新了輸入框的值,或初始化輸入框的值,需要回顯正確的位元組數

    #代碼:

    Vue.directive(&#39;wordlimit&#39;,{
      bind(el,binding){
        console.log(&#39;bind&#39;);
        let { value } = binding
        Vue.nextTick(() =>{
          //找到输入框是textarea框还是input框
          let current = 0
          let arr = Array.prototype.slice.call(el.children)
          for (let i = 0; i < arr.length; i++) {
            if(arr[i].tagName==&#39;TEXTAREA&#39; || arr[i].tagName==&#39;INPUT&#39;){
              current = i
            }
          }
      
          //更新当前输入框的字节数
          el.children[el.children.length-1].innerHTML = el.children[current].value.replace(/[^\x00-\xff]/g,&#39;**&#39;).length +&#39;/&#39;+value//eslint-disable-line
        })
      },
      update(el,binding){
        console.log(&#39;update&#39;);
        let { value } = binding
        Vue.nextTick(() =>{
          //找到输入框是textarea框还是input框
          let current = 0
          let arr = Array.prototype.slice.call(el.children)
          for (let i = 0; i < arr.length; i++) {
            if(arr[i].tagName==&#39;TEXTAREA&#39; || arr[i].tagName==&#39;INPUT&#39;){
              current = i
            }
          }
      
          //更新当前输入框的字节数
          el.children[el.children.length-1].innerHTML = el.children[current].value.replace(/[^\x00-\xff]/g,&#39;**&#39;).length +&#39;/&#39;+value//eslint-disable-line
        })
      },
      inserted(el,binding){
        console.log(&#39;inserted&#39;);
        let { value } = binding
    
        //找到输入框是textarea框还是input框
        let current = 0
        let arr = Array.prototype.slice.call(el.children)
        for (let i = 0; i < arr.length; i++) {
          if(arr[i].tagName==&#39;TEXTAREA&#39; || arr[i].tagName==&#39;INPUT&#39;){
            current = i
          }
        }
    
        //创建包裹字数限制的元素,并定位布局在textarea和input框上
        let div = document.createElement(&#39;div&#39;)
        if(el.children[current].tagName==&#39;TEXTAREA&#39;){//是textarea,定位在右下角
          div.style = &#39;color:#909399;position:absolute;font-size:12px;bottom:5px;right:10px;&#39;
        }else{
          let styStr = &#39;&#39;
          if(!el.classList.contains(&#39;is-disabled&#39;)){//input框不是置灰的状态则添加背景颜色
            styStr = &#39;background:#fff;&#39;
          }
          div.style = &#39;color:#909399;position:absolute;font-size:12px;bottom:2px;right:10px;line-height:28px;height:28px;&#39;+styStr
        }
    
        div.innerHTML = &#39;0/&#39;+ value
        el.appendChild(div)
        el.children[current].style.paddingRight = &#39;60px&#39;
    
        el.oninput = () =>{
          let val = el.children[current].value
          val = val.replace(/[^\x00-\xff]/g,&#39;**&#39;) //eslint-disable-line
          // 字数限制的盒子插入到el后是最后一个元素
          el.children[el.children.length-1].innerHTML = val.length + &#39;/&#39; + value
          if(val.length>value){
            let cnLen = 0 //一个字节的字数
            let enLen = 0 //两个字节的字数
    
            if(val.match(/[^**]/g) && val.match(/[^**]/g).length){
              enLen = val.match(/[^**]/g).length // 计算一个字节的字数
    
              //一个字节两个字节都有的情况
              if((value - val.match(/[^**]/g).length)>0){
                cnLen = Math.floor((value - val.match(/[^**]/g).length)/2)
              }else{
                cnLen = 0
              }
            }else{ //全部两个字节的情况
              enLen = 0
              cnLen = Math.floor(value/2)
            }
    
            if(enLen>value){
              enLen = value
            }
    
            //超过限定字节数则截取
            el.children[current].value = el.children[current].value.substr(0,enLen+cnLen)
    
            //更新当前输入框的字节数
            el.children[el.children.length-1].innerHTML = el.children[current].value.replace(/[^\x00-\xff]/g,&#39;**&#39;).length +&#39;/&#39;+value//eslint-disable-line
    
          }
        }
    
      },
    })

    使用:

    <el-input type="textarea" rows="3" v-wordlimit="20" v-model="value"></el-input>

    3、v-anthor

    需求:點擊某個元素(通常是標題、副標題之類的),動畫捲動到對應的內容區塊

    想法:

    • 計時器使用window. scrollBy
    • 不考慮ie的話,可直接使用 window.scrollBy({ top: ,left:0,behavior:'smooth' })

    #程式碼:

    Vue.directive(&#39;anchor&#39;,{
      inserted(el,binding){
        let { value } = binding
        let timer = null
        el.addEventListener(&#39;click&#39;,function(){
          // 当前元素距离可视区域顶部的距离
          let currentTop = el.getBoundingClientRect().top
          animateScroll(currentTop)
        },false)
        
        function animateScroll(currentTop){
          if(timer){
            clearInterval(timer)
          }
          let c = 9
          timer = setInterval(() =>{
            if(c==0){
              clearInterval(timer)
            }
            c--
            window.scrollBy(0,(currentTop-value)/10)
          },16.7)
        }
    
      }
    })

    使用:

    <div class="box" v-anchor="20" style="color:red;">是的</div>

    4、v-hasRole

    需求:根據系統角色新增或刪除對應元素

    程式碼:

    Vue.directive(&#39;hasRole&#39;,{
      inserted(el,binding){
        let { value } = binding
        let roles = JSON.parse(sessionStorage.getItem(&#39;userInfo&#39;)).roleIds
    
        if(value && value instanceof Array && value.length>0){
    
          let hasPermission = value.includes(roles)
    
          if(!hasPermission){
            el.parentNode && el.parentNode.removeChild(el)
          }
        }else{
          throw new Error(`请检查指令绑定的表达式,正确格式例如 v-hasRole="[&#39;admin&#39;,&#39;reviewer&#39;]"`)
        }
      }
    })

    更多程式相關知識,請造訪:程式設計入門! !

    以上是vue中值得了解的4個自訂指令(實用分享)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述:
    本文轉載於:juejin.cn。如有侵權,請聯絡admin@php.cn刪除