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>


相关文章
|
3天前
|
JavaScript 前端开发 CDN
vue3速览
vue3速览
12 0
|
3天前
|
设计模式 JavaScript 前端开发
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
|
3天前
|
JavaScript API
Vue3 官方文档速通(中)
Vue3 官方文档速通(中)
18 0
|
3天前
|
缓存 JavaScript 前端开发
Vue3 官方文档速通(上)
Vue3 官方文档速通(上)
20 0
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
8 1
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
7 0
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
6 0
|
3天前
|
JavaScript 前端开发 API
Vue3 系列:从0开始学习vue3.0
Vue3 系列:从0开始学习vue3.0
9 1
|
3天前
|
网络架构
Vue3 系列:vue-router
Vue3 系列:vue-router
8 2
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之一:基础项目构建
Vue3+Vite+Pinia+Naive后台管理系统搭建之一:基础项目构建
7 1