vue2.0自定义指令

1、分类

(1)私有自定义指令

(2)全局自定义指令

2、 私有自定义指令

(1)基本使用

  • 在每个vue组建中,可以在directives节点下声明私有自定义指令

  • 形参中el是绑定了此指令原生的DOM对象,是固定写法

  • v-是一个固定写法,自定义对象不需要写v-

  • 当指令第一次被绑定到元素上的时候,会立即触发bind函数

<h1 v-color>App 根组件</h1>
​
<script>
export default {
  directives: {
    color: {
      bind(el) {
        el.style.color = "red";
      },
    },
  },
};
</script>

(2)binding.value获取指令绑定的值

注意:不是一定叫binding,只是官方约定是binding

<h1 v-color="color">App 根组件</h1>
<p v-color="'red'">测试</p>
​
<script>
export default {
  data() {
    return {
      color: "blue",
    };
  },
  directives: {
    color: {
      bind(el, binding) {
        el.style.color = binding.value;
      },
    },
  },
};
</script>

(3)update函数

每次DOM更新时被使用

directives: {
  color: {
    bind(el, binding) {
      el.style.color = binding.value;
    },
    update(el, binding) {
      el.style.color = binding.value;
    }
  }
}

(4)函数简写

bind和update函数中逻辑相同,则对象格式的自定义函数可以简写成函数格式:(color不是规定的,是需要什么写什么)

directives: {
    color(el, binding) {
      el.style.color = binding.value;
    }
  }
}

3、全局自定义指令

  • 全局共享的自定义指令需要通过进行声明

  • 参数1:字符串,表示全局自定义指令的名字

  • 参数2:对象,用来接收指令的参数值

  • 全局声明的过滤器和指令在main.js中

  • 方法2常用

  • 全局自定义指令:Vue.directive('指令名字', function (el, binding) {})

  • 过滤器:Vue.filter('过滤器名字',function(){})

//方法1
Vue.directive('color', {
  bind(el, binding) {
    el.style.color = binding.value
  },
  update(el, binding) {
    el.style.color = binding.value
  },
})
​
//方法2
Vue.directive('color', function (el, binding) {
  el.style.color = binding.value
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值