Skip to content

自定义指令

基本使用

html

<script setup lang='ts'>
import { ref, reactive, Directive, DirectiveBinding } from 'vue'

import Menu from '../Menu/menu.vue';

type Dir = {
  background:string,
  name:string
}//用的不多可以不用传value的泛型

const vMove: Directive = {
  created() {  },
  beforeMount() {  },
  mounted(el:HTMLElement,dir:DirectiveBinding<Dir>) {//用的不多可以不用传Dir value的泛型
    // arg:canshu  
    console.log(dir.arg); 
    // modifiers:xiushifu
    console.log(dir.modifiers); 
    // value:值
    console.log(dir.value);
    el.style.backgroundColor = dir.value.background
  },//常用
  beforeUpdate() {  },
  updated() {  },//常用
  beforeUnmount() {  },
  unmounted() {  } //常用
}
</script>

<template>
  <div class="layout">
    <Menu v-move:canshu.xiushifu="{background:'red',name:'name'}"></Menu>
  </div>
</template>

函数简写

只想在 mountedupdated 时触发相同行为,而不关心其他钩子函数

typescript
import { ref, reactive, Directive, DirectiveBinding } from 'vue'

import Menu from '../Menu/menu.vue';

type Dir = {
  background:string,
  name:string
}//用的不多可以不用传value的泛型

const vMove: Directive = (el: HTMLElement, dir: DirectiveBinding<Dir>) => {
  // arg:canshu  
  console.log(dir.arg);
  // modifiers:xiushifu
  console.log(dir.modifiers);
  // value:值
  console.log(dir.value);
  el.style.backgroundColor = dir.value.background
}