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>


相关文章
|
1天前
|
JavaScript 定位技术 API
在 vue3 中使用高德地图
在 vue3 中使用高德地图
8 0
|
2天前
vue3 键盘事件 回车发送消息,ctrl+回车 内容换行
const textarea = textInput.value.textarea; //获取输入框元素
9 3
|
4天前
|
JavaScript 前端开发 CDN
vue3速览
vue3速览
14 0
|
4天前
|
设计模式 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
|
4天前
|
JavaScript 前端开发 安全
Vue3官方文档速通(下)
Vue3官方文档速通(下)
15 0
|
4天前
|
JavaScript API
Vue3 官方文档速通(中)
Vue3 官方文档速通(中)
20 0
|
4天前
|
缓存 JavaScript 前端开发
Vue3 官方文档速通(上)
Vue3 官方文档速通(上)
26 0
|
4天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
9 1
|
4天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
11 0
|
4天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
9 0