Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue3 directives

作者:ら非你不取丶   发布日期:2025-06-26   浏览:22

// Vue 3 Directives 示例代码

<template>
  <div>
    <p v-focus>这段文本会自动聚焦。</p>
    <input v-model="message" v-custom-directive />
  </div>
</template>

<script>
import { defineComponent, directive } from 'vue';

export default defineComponent({
  data() {
    return {
      message: ''
    };
  },
  directives: {
    focus: {
      mounted(el) {
        // 当元素挂载时,自动聚焦
        el.focus();
      }
    },
    customDirective: {
      mounted(el, binding, vnode, prevVnode) {
        // 自定义指令的逻辑
        console.log('Custom Directive Applied', binding.value);
        el.style.backgroundColor = 'yellow';
      }
    }
  }
});
</script>

<style scoped>
/* 样式可以根据需要添加 */
</style>

解释说明

  1. v-focus 指令:

    • focus 是一个自定义指令,它在元素挂载时调用 el.focus() 方法,使元素自动获得焦点。
    • 这个指令非常简单,只包含一个 mounted 钩子函数。
  2. v-custom-directive 指令:

    • customDirective 是另一个自定义指令,它在元素挂载时改变元素的背景颜色为黄色,并在控制台输出一些信息。
    • 它也只包含一个 mounted 钩子函数,但你可以根据需要添加更多的钩子函数(如 updatedbeforeUnmount 等)。
  3. 数据绑定:

    • 使用 v-model 绑定输入框的值到组件的 data 中的 message 属性。
  4. 注册指令:

    • 在组件的 directives 选项中注册自定义指令,以便在模板中使用。

希望这个示例能帮助你理解 Vue 3 的自定义指令。

上一篇:vue 调用子组件方法

下一篇:vue父组件如何向子组件中传递数据

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站