Vue3 自定义指令

简介: Vue3 自定义指令

自定义指令:常用于封装一些 DOM 操作,提高代码的复用性

语法格式:

// 完整写法
const 指令名 = {
  mounted: (el, binding) => {},
  updated: (el, binding) => {}
}
 
// 简写
const 指令名 = (el, binding) => {}
 
// 选项式写法
export default {
  ......
  directives: {
    // 完整写法
    big: {
      mounted: (el, binding) => {},
      updated: (el, binding) => {}
    },
    // 简写
    bigs(el, binding) {}
  }
}

自定义指令【完整写法】:

<template>
  <p>当前的num值是:<span v-text="num"></span></p>
  <p>放大10倍的num值是:<span v-big="num"></span></p>
  <button @click="num++">点击num+1</button>
</template>
 
<script setup>
import { ref } from "vue";
let num = ref(1);
// 创建自定义指令
const vBig = {
  // 绑定的元素挂载时执行
  mounted: (el, binding) => {
    console.log(el); // 绑定指令的 DOM 元素
    console.log(binding); // 绑定指令的对象
    el.innerText = binding.value * 10;
  },
  // 绑定的值更新时执行
  updated: (el, binding) => {
    console.log(el); // 绑定指令的 DOM 元素
    console.log(binding); // 绑定指令的对象
    el.innerText = binding.value * 10;
  }
}
</script>

自定义指令【简写】:

<template>
  <p>当前的num值是:<span v-text="num"></span></p>
  <p>放大10倍的num值是:<span v-big="num"></span></p>
  <button @click="num++">点击num+1</button>
</template>
 
<script setup>
import { ref } from "vue";
let num = ref(1);
// 简写:在 mounted 和 updated 时执行
const vBig = (el, binding) => {
  console.log(el); // 绑定指令的 DOM 元素
  console.log(binding); // 绑定指令的对象
  el.innerText = binding.value * 10;
}
</script>


相关文章
|
2天前
vue3【实战】语义化首页布局
vue3【实战】语义化首页布局
16 2
|
2天前
|
存储 容器
vue3【实战】来回拖拽放置图片
vue3【实战】来回拖拽放置图片
10 2
|
2天前
|
JavaScript 开发工具 开发者
vue3【提效】使用 VueUse 高效开发(工具库 @vueuse/core + 新增的组件库 @vueuse/components)
vue3【提效】使用 VueUse 高效开发(工具库 @vueuse/core + 新增的组件库 @vueuse/components)
12 1
|
2天前
|
API
Pinia 实用教程【Vue3 状态管理】状态持久化 pinia-plugin-persistedstate,异步Action,storeToRefs(),修改State的 $patch,$reset
Pinia 实用教程【Vue3 状态管理】状态持久化 pinia-plugin-persistedstate,异步Action,storeToRefs(),修改State的 $patch,$reset
13 1
|
2天前
|
JavaScript
vue3 【提效】自动注册组件 unplugin-vue-components 实用教程
vue3 【提效】自动注册组件 unplugin-vue-components 实用教程
8 1
|
3天前
|
JavaScript API
vue3【实用教程】组件(含父子组件传值 defineProps,自定义事件 defineEmits,defineProps,插槽 slot,动态组件 :is 等)
vue3【实用教程】组件(含父子组件传值 defineProps,自定义事件 defineEmits,defineProps,插槽 slot,动态组件 :is 等)
13 1
|
2天前
|
JavaScript 网络架构
vue3 【提效】自动路由(含自定义路由) unplugin-vue-router 实用教程
vue3 【提效】自动路由(含自定义路由) unplugin-vue-router 实用教程
11 0
vue3 【提效】自动路由(含自定义路由) unplugin-vue-router 实用教程
|
2天前
vue3 【提效】自动导入框架方法 unplugin-auto-import 实用教程
vue3 【提效】自动导入框架方法 unplugin-auto-import 实用教程
12 0
|
2天前
vue3 【提效】全局布局 vite-plugin-vue-layouts 实用教程
vue3 【提效】全局布局 vite-plugin-vue-layouts 实用教程
14 0
|
3天前
手写 vue3 的 ref,reactive 和 watchEffect
手写 vue3 的 ref,reactive 和 watchEffect
9 0