Vue 3 迁移策略笔记—— 第6节:自定义指令

编程入门 行业动态 更新时间:2024-10-24 10:18:13

Vue 3 迁移策略笔记—— 第6节:<a href=https://www.elefans.com/category/jswz/34/1771438.html style=自定义指令"/>

Vue 3 迁移策略笔记—— 第6节:自定义指令

前言

本笔记主要基于官方文档《迁移策略——自定义指令》汇总而来。如有理解出入,请以官方文档为主。建议您以官方文档为主,本文为辅。这样您可以“以自己为主”审视的阅读,从而不被我的观点带偏。

概述

为了更好的与组件生命周期保持一致,Vue 3.x 对自定义指令的钩子函数进行了重命名。

Vue 2.x 自定义指令的声明周期

  • bind——指令绑定到元素时触发,只触发一次;
  • inserted——绑定元素被插入父DOM时触发
  • update——当元素更新而子元素还没有更新时触发;
  • componentUpdated——组件和子组件更新完成后触发;
  • unbind——接触绑定时触发,只触发一次;

Vue 3.x 自定义指令的声明周期

  • beforeMount——替代bind
  • mounted ——替代inserted
  • beforeUpdate——移除Vue2.x 中的update,用beforeUpdateupdated 来替代
  • updated
  • beforeUnmount——卸载元素前调用
  • unmounted ——替代unbind

自定义指令用法

局部用法:

<template><div><p v-highlight="'yellow'">Highlight this text bright yellow</p></div>
</template><script>
export default {name: 'customDirective',directives: {highlight: {beforeMount(el, binding, vnode, prevVnode) {el.style.background = binding.value;console.log(el);console.log(binding);console.log(vnode);console.log(prevVnode);}}}
};
</script>

全局用法:

import { createApp } from 'vue'
import App from './App.vue'const app = createApp(App)app.directive('focus', {// When the bound element is mounted into the DOM...mounted(el) {// Focus the elementconsole.log(el);el.focus()}
})
app.mount('#app')

用法详细说明可查阅:《Vue3.0 directive的使用说明》

instance 的变动

在 Vue 3.x 中,绑定组件的实例(instance)从 Vue 2.x 的vnode移到了binding中:

Vue 2.x :

bind(el, binding, vnode) {const vm = vnode.context
}

Vue 3.x :

mounted(el, binding, vnode) {const vm = binding.instance
}

本系列目录

  • Vue 3 迁移策略笔记—— 第1节:v-for 中的 Ref 数组

  • Vue 3 迁移策略笔记—— 第2节:Async Components 异步组件

  • Vue 3 迁移策略笔记—— 第3节:Attribute Coercion Behavior (属性强制行为)

  • Vue 3 迁移策略笔记——第4节:$attrs 包括class&style

  • Vue 3 迁移策略笔记—— 第5节:移除 $children

  • Vue 3 迁移策略笔记—— 第6节:自定义指令

  • Vue 3 迁移策略笔记—— 第7节:自定义元素交互

  • Vue 3 迁移策略笔记—— 第8节:Data 选项

  • Vue 3 迁移策略笔记—— 第9节:新增 emits 选项

  • Vue 3 迁移策略笔记—— 第10节:事件 API

  • Vue 3 迁移策略笔记—— 第11节:移除过滤器

  • Vue 3 迁移策略笔记—— 第12节:片段

  • Vue 3 迁移策略笔记—— 第13节:函数式组件

  • Vue 3 迁移策略笔记—— 第14节:全局 API

  • Vue 3 迁移策略笔记—— 第15节:全局 API 的 tree shaking

  • Vue 3 迁移策略笔记—— 第16节:Inline Template 属性

  • Vue 3 迁移策略笔记—— 第17节:Key 属性

  • Vue 3 迁移策略笔记—— 第18节:按键修饰符

  • Vue 3 迁移策略笔记—— 第19节:移除 $listeners

  • Vue 3 迁移策略笔记—— 第20节:Props 的默认值函数不能访问this

  • Vue 3 迁移策略笔记—— 第21节:渲染函数 API

  • Vue 3 迁移策略笔记—— 第22节:Slots 的统一

  • Vue 3 迁移策略笔记—— 第23节:Transition Class 的变化

  • Vue 3 迁移策略笔记—— 第24节:Transition Group 不再需要设置根元素

  • Vue 3 迁移策略笔记—— 第25节:v-on.native修饰符被移除

  • Vue 3 迁移策略笔记—— 第26节:在组件上使用 v-model 的变化

  • Vue 3 迁移策略笔记—— 第27节:v-if 和 v-for 的优先级

  • Vue 3 迁移策略笔记—— 第28节:v-bind 合并行为

  • Vue 3 迁移策略笔记—— 第29节:数组的监听

更多推荐

Vue 3 迁移策略笔记—— 第6节:自定义指令

本文发布于:2024-03-13 02:55:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1733029.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   指令   策略   笔记   Vue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!