vue 自定义指令

vue 自定义指令

全局注册

const app = Vue.createApp({})
// 注册一个全局自定义指令 `v-focus`
app.directive('focus', {
  // 当被绑定的元素插入到 DOM 中时……
  mounted(el) {
    // Focus the element
    el.focus()
  }
})

局部注册

	data(){
	return {}
	},
    directives:{
        focus: {
            mounted(el, binding) {
                console.log(el);
                console.log(binding);
                el.style.position = 'fixed'
                // binding.arg is an argument we pass to directive
                const s = binding.arg || 'top'
                el.style[s] = binding.value + 'px'
            }
        }
    },

模板中使用

<button v-focus:[direction]="200">aaa</button>//direction等下介绍

钩子函数

import { createApp } from 'vue'
const app = createApp({})

// 注册
app.directive('my-directive', {
  // 指令是具有一组生命周期的钩子:
  // 在绑定元素的父组件挂载之前调用
  beforeMount() {},
  // 绑定元素的父组件挂载时调用
  mounted() {},
  // 在包含组件的 VNode 更新之前调用
  beforeUpdate() {},
  // 在包含组件的 VNode 及其子组件的 VNode 更新之后调用
  updated() {},
  // 在绑定元素的父组件卸载之前调用
  beforeUnmount() {},
  // 卸载绑定元素的父组件时调用
  unmounted() {}
})

// 注册 (功能指令)
app.directive('my-directive', () => {
  // 力扣 – 中文网 助你高效提升编程技能 https://www.javascriptc.com/special/leetcode/
// 这将被作为 `mounted` 和 `updated` 调用 在局部注册也一样使用箭头函数就代表默认mounted或者updated
})

// getter, 如果已注册,则返回指令定义
const myDirective = app.directive('my-directive')

钩子函数的参数

el
指令绑定到的元素。这可用于直接操作 DOM。
binding
instance:使用指令的组件实例。
value:传递给指令的值。例如,在 v-my-directive=“1 + 1” 中,该值为 2。
oldValue:先前的值,仅在 beforeUpdate 和 updated 中可用。值是否已更改都可用。
arg:参数传递给指令 (如果有)。例如在 v-my-directive:foo 中,arg 为 “foo”。
modifiers:包含修饰符 (如果有) 的对象。例如在 v-my-directive.foo.bar 中,修饰符对象为 {foo: true,bar: true}。
dir:一个对象,在注册指令时作为参数传递。例如,在以下指令中

dir
app.directive(‘focus’, {
mounted(el) {
el.focus()
}
})
dir将是以下对象
{
mounted(el) {
el.focus()
}
}

vnode
上面作为 el 参数收到的真实 DOM 元素的蓝图。
prevNode
上一个虚拟节点,仅在 beforeUpdate 和 updated 钩子中可用。
注意:除了 el 之外,你应该将这些参数视为只读,并且永远不要修改它们。如果你需要跨钩子共享信息,建议通过元素的自定义数据属性集 (opens new window)进行共享。

动态指令参数

<button v-focus:[direction]="200">aaa</button>
//此时这里的direction和200都可以使用组件data中定义的属性

在这里插入图片描述

函数简写

app.directive('pin', (el, binding) => {
  el.style.position = 'fixed'
  const s = binding.arg || 'top'
  el.style[s] = binding.value + 'px'
}) //此时只在钩子函数mounted和updated里面起作用

对象字面量,在组件中使用

官网

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值