vue中的自定义指令如何使用

自定义指令是用来干什么的呢?     获取标签,扩展额外的功能

有两种注册方法:

① 全局注册

Vue.directive('指令名',{
     // 可以对el标签扩展额外功能
     inserted (el) {},
     //   bind函数只调用1次: 当指令第一次绑定到元素时调用,当DOM更新时bind函数不会被触发。
     // 如果上面指令赋值,则接收第二个参数,官方指定叫做binding
      bind (el,binding) {},
      // update函数会在每次DOM更新时被调用。
      update(el, binding) {},
       // 指令所在组件的 VNode及其子 VNode全部更新后调用。
      componentUpdated() {},
      // 只调用一次,指令与元素解绑时调用
      unbind() {},
})

② 局部注册

directives {
//focus 是指令名
    focus: {
     // 可以对el标签扩展额外功能
     inserted (el) {},
     //   bind函数只调用1次: 当指令第一次绑定到元素时调用,当DOM更新时bind函数不会被触发。
     // 如果上面指令赋值,则接收第二个参数,官方指定叫做binding
      bind (el,binding) {},
      // update函数会在每次DOM更新时被调用。
      update(el, binding) {},
       // 指令所在组件的 VNode及其子 VNode全部更新后调用。
      componentUpdated() {},
      // 只调用一次,指令与元素解绑时调用
      unbind() {},
    }

    
}

tip:全局注册是directive节点, 局部注册是 directives节点

我们来稍微用一下全局指令:

全局指令在main.js中

/* 
全局自定义指令
*/
Vue.directive('focus', {
  inserted(el) {
    el.focus()
  }
})

自己需要用的vue文件

<div>
      <h2>自定义指令</h2>
      <input type="text" v-focus />
    </div>

我们再来用一下局部指令:

在自己需要的vue文件中:

<div>
      <h2>局部指令</h2>
      <p v-colors>局部指令</p>
</div>
directives: {
    colors: {
      inserted (el) {
        el.style.color = 'red'
      },
    },
  },

自定义指令传值:

main.js中:

/* 
全局自定义指令传值
*/
Vue.directive("pinkColor", {
  inserted(el, binding) {
    el.style.color = binding.value;
  },
});

自己vue文件中:

注意:传的值是字符串还是变量

① 字符串用法:

<template>
  <div>
    <div>
      <h2>全局指令传值</h2>
      <!-- v-pinkColor="'pink'" 注意是字符串 -->
      <p v-pinkColor="'pink'">全局指令传值</p>
    </div>
  </div>
</template>

② 变量用法

<template>
  <div>
    <div>
      <p v-pinkColor="colorStr">全局自定义指令传值变量用法</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      colorStr: "pink",
    };
  }
};
</script>

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值