vue自定义指令VNode详解

vue自定义指令VNode详解1 自定义指令钩子函数 Vue directive my directive bind function 做绑定的准备工作 比如添加事件监听器 或是其他只需要执行一次的复杂操作 inserted function newValue oldValue 被绑定元素插入父节点时调用 update f

1、自定义指令钩子函数

Vue.directive('my-directive', { bind: function () { 
    // 做绑定的准备工作 // 比如添加事件监听器,或是其他只需要执行一次的复杂操作 }, inserted: function (newValue, oldValue) { 
    // 被绑定元素插入父节点时调用 }, update: function (newValue, oldValue) { 
    // 根据获得的新值执行对应的更新 // 对于初始值也会被调用一次 }, unbind: function () { 
    // 做清理工作 // 比如移除在 bind() 中添加的事件监听器 } })

指令定义函数提供了几个钩子函数(可选):

  • bind: 只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个在绑定时执行一次的初始化动作。
  • inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。
  • update: 所在组件的 VNode 更新时调用,但是可能发生在其孩子的 VNode 更新之前。指令的值可能发生了改变也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新 (详细的钩子函数参数见下)。
  • componentUpdated: 所在组件的 VNode 及其孩子的 VNode 全部更新时调用。
  • unbind: 只调用一次, 指令与元素解绑时调用。
    接下来我们来看一下钩子函数的参数 (包括 el,binding,vnode,oldVnode) 。


2、钩子函数参数

钩子函数被赋予了以下参数:

  • el: 指令所绑定的元素,可以用来直接操作 DOM 。
  • binding: 一个对象,包含以下属性:
    • name: 指令名,不包括 v- 前缀。
    • value: 指令的绑定值, 例如: v-my-directive=”1 + 1”, value 的值是 2。
    • oldValue: 指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。无论值是否改变都可用。
    • expression: 绑定值的字符串形式。 例如 v-my-directive=”1 + 1” , expression 的值是 “1 + 1”。
    • arg: 传给指令的参数。例如 v-my-directive:foo, arg 的值是 “foo”。
      modifiers: 一个包含修饰符的对象。 例如: v-my-directive.foo.bar, 修饰符对象 modifiers 的值是 { foo: true, bar: true }。


  • vnode: Vue 编译生成的虚拟节点
  • oldVnode: 上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。

3、VNode接口

export default class VNode { tag: string | void; data: VNodeData | void; children: ?Array 
    
      ; text: string | 
     void; elm: Node | 
     void; ns: string | 
     void; context: Component | 
     void; 
     // rendered in this component's scope functionalContext: Component | 
     void; 
     // only for functional component root nodes key: string | number | 
     void; componentOptions: VNodeComponentOptions | 
     void; componentInstance: Component | 
     void; 
     // component instance parent: VNode | 
     void; 
     // component placeholder node raw: boolean; 
     // contains raw HTML? (server only) isStatic: boolean; 
     // hoisted static node isRootInsert: boolean; 
     // necessary for enter transition check isComment: boolean; 
     // empty comment placeholder? isCloned: boolean; 
     // is a cloned node? isOnce: boolean; 
     // is a v-once node? asyncFactory: 
     Function | 
     void; 
     // async component factory function asyncMeta: 
     Object | 
     void; isAsyncPlaceholder: boolean; ssrContext: 
     Object | 
     void; constructor ( tag?: string, data?: VNodeData, children?: ? 
     Array 
     
       , text?: string, elm?: Node, context?: Component, componentOptions?: VNodeComponentOptions, asyncFactory?: 
      Function ) { 
      this.tag = tag 
      this.data = data 
      this.children = children 
      this.text = text 
      this.elm = elm 
      this.ns = 
      undefined 
      this.context = context 
      this.functionalContext = 
      undefined 
      this.key = data && data.key 
      this.componentOptions = componentOptions 
      this.componentInstance = 
      undefined 
      this.parent = 
      undefined 
      this.raw = 
      false 
      this.isStatic = 
      false 
      this.isRootInsert = 
      true 
      this.isComment = 
      false 
      this.isCloned = 
      false 
      this.isOnce = 
      false 
      this.asyncFactory = asyncFactory 
      this.asyncMeta = 
      undefined 
      this.isAsyncPlaceholder = 
      false } 
      // DEPRECATED: alias for componentInstance for backwards compat. 
      /* istanbul ignore next */ get child (): Component | 
      void { 
      return 
      this.componentInstance } } export 
      const createEmptyVNode = (text: string = 
      '') => { 
      const node = 
      new VNode() node.text = text node.isComment = 
      true 
      return node } export 
      function createTextVNode (val: string | number) { 
        
      return 
      new VNode( 
      undefined, 
      undefined, 
      undefined, 
      String(val)) } 
      // optimized shallow clone 
      // used for static nodes and slot nodes because they may be reused across 
      // multiple renders, cloning them avoids errors when DOM manipulations rely 
      // on their elm reference. export 
      function cloneVNode (vnode: VNode, deep?: boolean): VNode { 
        
      const cloned = 
      new VNode( vnode.tag, vnode.data, vnode.children, vnode.text, vnode.elm, vnode.context, vnode.componentOptions, vnode.asyncFactory ) cloned.ns = vnode.ns cloned.isStatic = vnode.isStatic cloned.key = vnode.key cloned.isComment = vnode.isComment cloned.isCloned = 
      true 
      if (deep && vnode.children) { cloned.children = cloneVNodes(vnode.children) } 
      return cloned } export 
      function cloneVNodes (vnodes: Array 
        
          , deep?: boolean) 
        : Array<VNode> { 
        
      const len = vnodes.length 
      const res = 
      new 
      Array(len) 
      for ( 
      let i = 
      0; i < len; i++) { res[i] = cloneVNode(vnodes[i], deep) } 
      return res } 
      
    

4、VNode

不存在父节点:

这里写图片描述

存在父节点:

这里写图片描述

v-IME自定义指令示例:

import { log } from 'SUtil' const install = Vue => { let isBind = true let IMEService = '' let $this = new Vue({ data () { return { outEl: null, outVnode: null } }, watch: { outVnode (value, oldValue) { if (oldValue) { oldValue.componentInstance.isFocus = false } } } }) async function openIme (e, option) { 
       log.d('openIme', isBind, $this.$data.outVnode.componentInstance.percentValue) if ($this.$data.outEl && IMEService && isBind) { log.d('open') $this.$data.outEl.target.focus() let ret = await IMEService.open({ type: IMEService[option.type], track: Number.parseInt(option.track), w: Number.parseInt(option.w), h: Number.parseInt(option.h), x: Number.parseInt(option.x), y: Number.parseInt(option.y) }) if (ret.isSuccess) { console.log('输入法开启成功') } } } async function closeIme (e) { 
       log.d('closeIme', isBind, $this.$data.outVnode.componentInstance.percentValue) if ($this.$data.outEl && IMEService && isBind) { log.d('close') $this.$data.outVnode.componentInstance.isFocus = false let ret = await IMEService.close() if (ret.isSuccess) { console.log('输入法关闭成功') } } } Vue.directive('IME', { bind: function (el, binding, vnode) { 
       $this.$data.outVnode = vnode if (window.taf && window.taf.service.IMEService) { IMEService = window.taf.service.IMEService } else { log.e('IMEService 不存在') $this.$data.outVnode.componentInstance.$emit('error', '输入法故障') log.d('error', $this.$data.outVnode.componentInstance.percentValue) } }, inserted: function (el, binding, vnode) { 
       const inputDom = vnode.componentInstance.$el.querySelector('input') if (inputDom) { inputDom.addEventListener('focus', async focusEvent => { log.d('focus') $this.$data.outEl = focusEvent $this.$data.outVnode = vnode vnode.componentInstance.ctrlBlur = true openIme(focusEvent, binding.value) }) inputDom.addEventListener('click', async focusEvent => { log.d('click') $this.$data.outEl = focusEvent $this.$data.outVnode = vnode vnode.componentInstance.ctrlBlur = true openIme(focusEvent, binding.value) }) inputDom.addEventListener('blur', async focusEvent => { log.d('blur') $this.$data.outEl = focusEvent $this.$data.outVnode = vnode vnode.componentInstance.ctrlBlur = false closeIme(focusEvent) }) } isBind = true }, async unbind (el, binding, vnode) { log.d('unbind') if (window.taf && window.taf.service.IMEService) { IMEService = window.taf.service.IMEService } else { log.e('IMEService 不存在') $this.$data.outVnode.componentInstance.$emit('error', 'IMEService 不存在') log.d('error', $this.$data.outVnode.componentInstance.percentValue) } const inputDom = vnode.componentInstance.$el.querySelector('input') if (inputDom) { inputDom.removeEventListener('click', openIme) isBind = false await IMEService.close() } } }) } export default { install } 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/220221.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月17日 下午8:58
下一篇 2026年3月17日 下午8:58


相关推荐

  • splice方法最详细最全面的解释!!!

    splice方法最详细最全面的解释!!!文章目录前言一、splice方法官方文档节选二、根据文档测试方法一:方法二:方法三:方法四:总结前言在学前端的时候一直对splice方法不太清楚,今天特意总结了一下!一、splice方法官方文档节选查阅了splice方法的示例文档,如下:(不想看论述的,可以直接跳到下面看总结!)splice返回值:Array所属对象:ArrayTheelementstoaddtothearray.Ifyoudon’tspecifyanyelements,splice

    2026年3月6日
    5
  • 基于深度学习的人脸性别识别系统(含UI界面,Python代码)「建议收藏」

    基于深度学习的人脸性别识别系统(含UI界面,Python代码)「建议收藏」摘要:人脸性别识别是人脸识别领域的一个热门方向,本文详细介绍基于深度学习的人脸性别识别系统,在介绍算法原理的同时,给出Python的实现代码以及PyQt的UI界面。在界面中可以选择人脸图片、视频进行检测识别,也可通过电脑连接的摄像头设备进行实时识别人脸性别;可对图像中存在的多张人脸进行性别识别,可选择任意一张人脸框选显示结果,检测速度快、识别精度高。博文提供了完整的Python代码和使用教程,适合新入门的朋友参考,完整代码资源文件请转至文末的下载链接。

    2022年5月23日
    50
  • RedisClient的安装及基本使用[通俗易懂]

    RedisClient的安装及基本使用[通俗易懂]管理redis的可视化客户端目前较流行的有三个:RedisClient;RedisDesktopManager;RedisStudio.这里目前给大家介绍RedisClient的下载安装及基本使用。RedisClient是Redis客户端的GUI工具,使用Javaswt和jedis编写,可以方便开发者浏览Redis数据库。该软件支持简体中文,非常适合国内用户使用,不需要汉化就可以直接使用。RedisClient将redis数据以资源管理器的界面风格呈现给用户,可以帮助redis

    2022年8月31日
    7
  • 如何修改织梦系统后台登录名和密码听语音

    如何修改织梦系统后台登录名和密码听语音

    2021年9月20日
    49
  • goland 2021 激活码破解方法

    goland 2021 激活码破解方法,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月15日
    199
  • phpstorm使用教程

    phpstorm使用教程phpstorm 包含了 webstorm 的全部功能 更能够支持 php 代码 PhpStorm 是一个轻量级且便捷的 PHPIDE 其旨在提供用户效率 可深刻理解用户的编码 提供智能代码补全 快速导航以及即时错误检查 phpstorm 的好功能有很多很多 为我们快速有效地完成项目提供了很多的方便之处 下面我们就一窥它的神奇之处吧 先从捣鼓编辑器外观让我们看着顺眼些开始吧 1 修改整个

    2026年3月20日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号