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使用,这样更加简洁。大家可以去试试............