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

vue2 自定义指令

作者:冷宸枫   发布日期:2025-05-25   浏览:37

// 自定义指令示例代码

// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el) {
    // 聚焦元素
    el.focus()
  }
})

// 在组件中使用自定义指令
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  },
  // 或者在局部注册自定义指令
  directives: {
    // 注册一个局部自定义指令 `v-highlight`
    highlight: {
      bind (el, binding, vnode) {
        // 应用文本颜色
        el.style.color = binding.value || 'red';
      }
    }
  }
})

<!-- HTML -->
<div id="app">
  <!-- 使用全局自定义指令 v-focus -->
  <input v-focus />

  <!-- 使用局部自定义指令 v-highlight -->
  <p v-highlight="'blue'">{{ message }}</p>
</div>

解释说明:

  1. 全局自定义指令:通过 Vue.directive 方法注册一个全局自定义指令 v-focus,当带有该指令的元素被插入到 DOM 中时,自动聚焦该元素。
  2. 局部自定义指令:在组件选项中通过 directives 属性注册一个局部自定义指令 v-highlight,可以在模板中使用该指令来设置文本颜色。

上一篇: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 中文站