Vue实现自定义指令

123 阅读1分钟

自定义指令 directive

directive 文件夹 下autofocus.js 文件

import Vue from 'vue'
import { focus } from '@/utils/DOM'

Vue.directive('autofocus', {
  inserted(el) {
    focus(el)
  }
})

image.png

import Vue from 'vue'

// hack for autofocus on dynamic elements
const FOCUSABLE_ELEMENT_TAGS = [
  'INPUT',
  'SELECT',
  'TEXTAREA',
  'CHECKBOX',
  'RATIO'
]

export function focus(el) {
  let target
  if (FOCUSABLE_ELEMENT_TAGS.includes(el.tagName)) {
    target = el
  } else {
    for (const tag of FOCUSABLE_ELEMENT_TAGS) {
      const [matchedEl] = el.getElementsByTagName(tag.toLowerCase())
      if (matchedEl) {
        target = matchedEl
        break
      }
    }
  }
  Vue.nextTick(() => {
    target && target.focus()
  })
}

image.png

局部 focus 光标

<template>
  <div>
    <input v-focus type="text">
  </div>
</template>
<script>
const directives = {
  focus: {
    mounted(el) {
      el.focus()
    }
  }
}

export default {
  directives
}
</script>

自定义指令 添加颜色 高度

<template>
  <div>
    <input v-pos type="text">
  </div>
</template>
<script>
const directives = {
  pos: {
    mounted(el) {
      el.style.marginTop = '200px'
      el.style.background = 'red'
    }
  }
}

export default {
  directives
}
</script>

image.png

<template>
  <div>
    <input v-pos="200" v-focus type="text">
  </div>
</template>
<script>
const directives = {
  pos: {
    mounted(el, binding) {
      el.style.marginTop = binding.value + 'px'
      // el.style.background = 'red'
    }
  },
  focus: {
    mounted(el) {
      el.focus()
    }
  }
}

export default {
  directives
}
</script>

用于指令的刷新 添加 updated 更新

<template>
  <div>
    <input v-pos="200" v-focus type="text">
  </div>
</template>
<script>
const directives = {
  pos: {
    mounted(el, binding) {
      el.style.marginTop = binding.value + 'px'
      el.style.background = 'red'
    },
    //用于刷新指令
    updated(el, binding) {
      el.style.marginTop = binding.value + 'px'
    }
  },
  focus: {
    mounted(el) {
      el.focus()
    }
  }
}

export default {
  directives
}
</script>

局部自定义指令 使用箭头函数来实现

<template>
  <div>
    <input v-pos="200" type="text">
  </div>
</template>
<script>
const directives = {
  pos: (el, binding) => {
    el.style.marginTop = binding.value + 'px'
  },
  // pos1: {
  //   mounted(el, binding) {
  //     el.style.marginTop = binding.value + 'px'
  //   }
  // }
}

export default {
  directives
}
</script>

image.png