LOADING...

加载过慢请开启缓存(浏览器默认开启)

loading

Vue3 自定义指令

自定义指令directive

在Vue中除了像v-model 和 v-show这样的默认内置的指令外, Vue 也允许注册自定义指令。自定义指令用于对DOM 元素进行底层操作。

局部自定义指令

局部自定义指令类似局部组件,组件使用directives进行引用

定义


const vMoveDirective: Directive = {
  created: () => {
    console.log("初始化====>");
  },
  beforeMount(...args: Array<any>) {
    // 在元素上做些操作
    console.log("初始化一次=======>");
  },
  mounted(el: any, dir: DirectiveBinding<Value>) {
    el.style.background = dir.value.background;
    console.log("初始化========>");
  },
  beforeUpdate() {
    console.log("更新之前");
  },
  updated() {
    console.log("更新结束");
  },
  beforeUnmount(...args: Array<any>) {
    console.log(args);
    console.log("======>卸载之前");
  },
  unmounted(...args: Array<any>) {
    console.log(args);
    console.log("======>卸载完成");
  },

使用

<template>
  <button @click="show = !show">开关{{show}} ----- {{title}}</button>
  <Dialog  v-move-directive="{background:'green',flag:show}"></Dialog>
</template>

全局自定义指令

  • 在main.js中添加全局directive
  • 在3.0中创建vue实例的方式不再是new Vue,而是使用createApp方法进行创建

创建

import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

app.directive('focus', {
    mounted(el) {
        console.log(el);
        el.focus()
    }
})
app.mount('#app')

其它组件内使用

<template>
    <input v-focus>
</template>
img_show