自定义指令"/>
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
,用beforeUpdate
和updated
来替代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节:自定义指令
发布评论