vue2.x 自定义指令

在这里插入图片描述

1 概述

简介:除了核心功能默认内置的指令 (v-model, v-show 等),Vue 也允许注册自定义指令。

场景:
注意,在 Vue2.x 中,代码复用和抽象的主要形式是组件。
然而,有的情况下,你仍然需要对普通 DOM 元素进行底层操作,这时候就会用到自定义指令。

2 语法-示例

举个聚焦输入框的例子;

期望结果:页面打开时,input 自动获得焦点。
拓展:表单的 autofocus 属性 在移动端的 Safari 上不工作。

全局注册 “自定义指令”

Vue.directive()
指令配置项 & 配置项参数;

局部注册 “自定义指令”

directives: {
  focus: {
    // 指令的定义
    inserted: function (el) {
      el.focus()
    }
  }
}

tip: 配置项和钩子参数同上面 全局自定义指令的参数。

使用:可以在模板中任何元素上使用新的 v-focus property。

<input v-focus />

3 动态指令参数

语法:

<p v-pin:[direction]="200">Stick me 200px from the top of the page</p>

4 函数简写

// 简化前(配置项)
Vue.directive('color-swatch', {
  inserted: function (el, binding) {
    /* ... */
  },
})
// 简化后(直接的函数)
Vue.directive('color-swatch', function (el, binding) {
  el.style.backgroundColor = binding.value
})

5 指令绑定值为 对象字面量

如果指令需要多个值,可以传入一个 JS 对象字面量。

记住,指令函数能够接受所有合法的 JS 表达式。

<div v-demo="{ color: 'white', text: 'hello!' }"></div>
Vue.directive('demo', function (el, binding) {
  console.log(binding.value.color) // => "white"
  console.log(binding.value.text) // => "hello!"
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值