directive的生命周期和简单使用

<template>
  <lifeComponent v-demo="{color: 'red'}"></lifeComponent>
  </template>
 
  <script setup lang='ts'>
  import { ref, reactive } from 'vue'
  import type { Directive, DirectiveBinding } from 'vue'

  import lifeComponent from '../study/directive/lifeComponent.vue';
 
  type Dir = {
    color:string
  }
  // 自定义指令,使用v+自定义名称方便使用时通过 v-自定义名称 使用
  const vDemo:Directive  = {
    // 自定义指令的生命周期
    created() {
      console.log('created');
    },
    beforeMount() {
      console.log('beforeMount');
    },
    // dir是DirectiveBinding类型,Dir是定义的传入的对象类型限制,使用Dir泛型限制后有代码提示
    mounted(el:HTMLElement, dir:DirectiveBinding<Dir>, vNode, preNode) {
      console.log("获取该元素", el);
      console.log("获取该元素传入的值,例如修饰符、传入的对象", dir);
      console.log("获取该元素的虚拟dom", vNode);
      console.log("获取该元素的上一个虚拟dom", preNode);
      console.log('mounted');
      // 通过el设置color样式
      el.style.color = dir.value.color
    },
    beforeUpdate() {
      console.log('beforeUpdate','传入的值有修改是会走该生命周期');
    },
    updated() {
      console.log('updated','传入的值有修改是会走该生命周期');
    },
    beforeUnmount() {
      console.log('beforeUnmount','通过v-if在该生命周期会走该生命周期');
    },
    unmounted() {
      console.log('unmounted','通过v-if在该生命周期会走该生命周期');
    }
  }
  </script>
 
  <style scoped lang='scss'>
 
  </style>

posted on   ChoZ  阅读(5)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2023-02-08 css3中-webkit是什么意思

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示