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 element
        console.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
}

本系列目录

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值