Vue3中自定义指令

发布于:2025-05-31 ⋅ 阅读:(22) ⋅ 点赞:(0)

1. 认识自定义指令

  • 1.1. 在Vue的模板语法中有各种各样的质量:v-show,v-for, v-model等,除了使用这些指令外,Vue也允许我们来自定义自己的指令
    • 1.1.1. 注意:在Vue中,代码的复用和抽象主要还是通过组件;
    • 1.1.2. 通常在某些情况下,需要对DOM元素进行底层操作,这个时候就会用到自定义指令

1.2. 自定义指令分为两种:

  • 1.2.1. 全局指令:appdirective方法,可以在任意组件中被使用
  • 1.2.2. 局部指令:组件中通过的directives方法,只能在当前组件中使用

1.3. 自定义指令的简单案例: 当某个元素挂载完成后可以自动获取焦点

  • 1.3.1. 实现方式一: 使用默认的实现方式
  • 1.3.2. 实现方式二: 自定义一个v-focus的局部指令
    • 1.3.2.1. options实现方式

      • 自定义指令实现,需要在组件选项中使用directives
      • 它是一个对象,在对象中编写自定义指令的名称(注意:这里不需要加v-);
      • 自定义指令有一个生命周期,是在组件挂载后调用的mounted, 可以在其中完成操作
      • 代码如下:
          <script>
            export default {
              directives: {
                focus: {
                  mounted (el) {
                    // 生命周期的函数(自定义指令)
                    el?.focus()
                  }
                }
              }
            }
            </script>
        
    • 1.3.2.2. Composition Api 实现方式

      • 自定义局部指令, 必须v开头
      • 代码如下:
          <script setup>
            // 2. 方式二: 自定义局部指令, 必须v开头
            const vFocus = {
              mounted (el) {
                // 生命周期的函数(自定义指令)
                el?.focus()
              }
            }
          </script>
        
    • 1.3.3. 实现方式三: 自定义一个v-focus的全局指令

      • 代码如下:
        const app = createApp(App)
        //  自定义全局指令
        app.directive('focus', {
          mounted (el) {
            el.focus()
          }
        })
      
        app.mount('#app')
      

1.4. 自定义指令的生命周期

  • created: 在绑定元素的attribute或时间监听器被应用之前调用;

  • beforeMount: 当指令第一次绑定到元素并且挂载父组件之前调用;

  • mounted: 在绑定元素的父组件被挂载后调用;

  • beforeUpdate: 在更新包含组件的VNode之前调用;

  • updated: 在更新包含组件的VNode及其子组件的VNode更新后调用;

  • beforeUnmount: 在卸载绑定元素的父组件之前调用;

  • unmounted: 当指令与元素解除绑定且父组件已卸载时,只调用一次;

  • 代码如下:

      <script setup>
        const vWhy = {
          created () {
            console.log('created');
          },
          beforeMount () {
            console.log('beforeMount');
          },
          mounted(el) {
            console.log('mounted');
          },
          beforeUpdate () {
            console.log('beforeUpdate');
          },
          updated () {
            console.log('updated');
          },
          beforeUnmount () {
            console.log('beforeUnmount');
          },
          unmounted () {
            console.log('unmounted');
          }
        }
      </script>
    
    

1.5. 自定义指令参数和修饰符

  • 代码如下:
    <!-- 自定义指令的参数和修饰符
        v-model:title.lazy.trim="message"
        title: 指令参数 -> args -> arguments
        lazy: 修饰符 -> modifiers -> 懒加载
        trim: 修饰符 -> modifiers -> 去除空格
        message: 绑定的变量,值 -> value -> 最后赋值给title
       -->
      <input type="text" v-model:title.lazy.trim="message"> 
    
  • 案例代码如下:
      <template>
        <div class="app">
          // 1.参数-修饰符-值
          <h2 v-why:kobe.cba.abc="message" class="title">哈哈哈</h2>
    
          //  <!-- 2.价格拼接单位符号 -->
          <h2 v-unit>{{ 111 }}</h2>
        </div>
      </template>
    
      <script setup>
        import { ref } from 'vue';
        const price = ref(111);
        const unit = ref('¥')
        const message = ref('你好,李银河');
    
    
        const vWhy = {
          mounted(el, bindings) {
            el.textContent = bindings.value
          },
        }
      </script>
    

1.6. 统一抽取自定义全局指令

  • 1.6.1. 创建directives文件夹

    
        // 在main.js中引入
        import { useDirectives } from './01_自定义指令/directives/index.js'
        const app = createApp(App)
        useDirectives(app)
    
      ```
      
    
  • 1.6.2. directives下创建index.js统一导入导出所有自定义指令

       // 导入对应指令文件
       import  directiveUnit from "./unit";
    
       // 导出useDirective函数并执行指令
       export function useDirectives (app) {
         directiveUnit(app)
       } 
    
     ```
    
  • 1.6.3. 创建指令.js文件 (例如: unit.js)

       export default function directiveUnit (app) {
         app.directive('unit', {
           mounted (el, bindings) {
             //  获取默认文本值
             const defaultText = el.textContent;
             // 如果没传单位参数,设置默认值
             let unit = bindings.value; 
             if(!unit) {
               unit = '¥'
             }
             // 添加单位
             el.textContent = unit + defaultText
           }
         })
       }
    

1.7. 自定义指令时间格式化案例

  • 1.7.1. 创建ftime文件
    • 代码如下:
      // ftime.js
      import dayjs from "dayjs";
      export default function directiveFTime (app) {
        app.directive('ftime', {
          mounted (el, bindings) {
            // 1.获取时间,并且转化成毫秒
            let timestamp = el.textContent;
            if(timestamp.length === 10) {
              timestamp = timestamp * 1000
            }
        
            timestamp = Number(timestamp)
    
            // 2.获取传入的参数
            let value = bindings.value
            if(!value) {
              value = 'YYYY-MM-DD HH:mm:ss'
            }
    
            // 3.对时间进行格式化
            const formatTime = dayjs(defaultText).format(value)
            el.textContent = formatTime
          }
        })
      } 
    
  • 1.7.2. directives/index.js文件中引入ftiem文件
      import directiveFtime from "./ftime";
      export function useDirectives (app) {
        directiveFtime(app)
      } 
    
  • 1.7.3. 在main.js中引入useDirectives函数并执行指令
      import { useDirectives } from './01_自定义指令/directives/index.js'
    
      const app = createApp(App)
    
      useDirectives(app)
    
    
    在这里插入图片描述

网站公告

今日签到

点亮在社区的每一天
去签到