vue3 自定义指令详解


theme: mk-cute

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

Vue3 自定义指令详解

Vue中有v-if,v-for,v-bind,v-show,v-model...等等一系列方便快捷的指令 今天一起来了解一下vue里提供的自定义指令

Vue3 自定义指令生命周期

  • created 元素初始化的时候
  • beforeMount 指令绑定到元素后调用 只调用一次
  • mounted 元素插入父级dom调用
  • beforeUpdate 元素被更新之前调用
  • update 这个周期方法被移除 改用updated
  • beforeUnmount 在元素被移除前调用
  • unmounted 指令被移除后调用 只调用一次

指令生命周期示例

```js const Directive = { created() {}, beforeMount() {}, mounted() {}, beforeUpdate() {}, updated() {}, beforeUnmount() {}, unmounted() {} }

```

全局指令示例

input 聚焦
  • 该指令可自动聚焦输入框
  • 在main.js文件中编写指令
  • el是当前挂载元素

js import { createApp } from 'vue' const app = createApp({}) app.directive('focus', { // 当元素挂载时 mounted(el) { // 聚焦元素 el.focus() } }) - 在input框上写v-focus即可生效

元素 点击动效
  • 该指令可以点击反馈效果
  • 在main.js文件中引入公用css

css .button:active { transform: translateY(4px); } ```js import './main.css'

app.directive('active', { mounted(el) { el.classList.add('button') } }) ```

  • 在任何组件上挂载指令都会有上下动的特效

局部指令示例

input 聚焦
  • 指令代码编写在当前组件文件中
  • 仅在当前组件中生效

js directives: { focus: { mounted(el) { el.focus() } } }

自定义指令参数

  • el 元素本身
  • binding

    • intance 当前组件实例
    • value 指令传递的值
      • 例如<input v-focus="2"/>
    • oldValue 旧的值
      • 仅在 beforeUpdate 和 updated 中可用
    • arg 指令传递的参数
      • 例如<input v-focus:foo/>
    • modifiers 包含的修饰符
      • 例如<input v-focus.foo.bar/>
      • 修饰符对象为{foo: true,bar: true}
    • dir 一个对象,在注册指令时作为参数传递 ```js app.directive('active', {mounted(el) { el.classList.add('button') } })

      // dir是指 {mounted(el) { el.classList.add('button') } } ```

  • vnode 元素的虚拟dom
  • prevVnode 上一个虚拟dom 仅在 beforeUpdate 和 updated 中可用

总结

  • 指令也可以写在单独的一个文件夹内引入main.js用app.use使用,这样更加简洁。大家可以去试试............
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值