自定义指令

63 阅读1分钟

局部注册

<template>
<div>
    <h2>自定义指令</h2>
    //v-focus 自定义指令 直接使用即可
    <input v-focus placeholder="请输入文章" />
</div>
</template>
<script>
export default {
 directives: {
 //foucus 是我们自己定义的指令属性名
    focus: {
      inserted(el) {//这里的el就指的是input这个dom元素              //给这个dom元素添加方法   focus()
            el.focus()
        }
    }
}
}
</script>
<style lang='less'  scoped>
</style>

全局注册 在main.js文件中

 / 1自定义指令   
// Vue.directive('指令的名称','对象配置{}')
Vue.directive('focus', {
   inserted: function (el, binding) {
      onsole.log(el, 'elelele');
      console.log(binding, 'binding')//得到一个对象 里   面有 binding.value
      console.log(binding.value);  //abc
      el.focus()
      el.style.color = 'green'   //设置颜色的
  }
})

// 2 自定义指令  做按钮权限的
// Vue.directive('指令的名称','对象配置{}')
Vue.directive('allow', {
inserted: function (el, binding) {
//  1获取用户按钮权限的信息
const points =store.state.user.userInfo.roles.points
console.log('points', points);
//2 根据权限信息进行过滤
if (!points.includes(binding.value)) {
  // 没有权限就将改按钮隐藏起来
  el.style.display = 'none'
}

}
})