当前位置: 代码迷 >> 综合 >> Vue 自定义指令基本用法
  详细解决方案

Vue 自定义指令基本用法

热度:20   发布时间:2024-01-19 22:36:46.0

为什么需要自定义指令呢?

因为内置指令不满足需求。

下面看一下基本的创建自定义指令语法:

Vue.directive('focus',{inserted:function(el){//获取元素焦点el.focus();}})

自定义指令用法

<input type="text" v-focus>

下面看一下具体的代码。

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>自定义指令基本使用</title></head><body><div id="app"><input type="text" v-focus /></div><script src="vue.js"></script><script>Vue.directive("focus", {inserted: function (el) {//el:表示指令所绑定的元素el.focus();},});const vm = new Vue({el: "#app",data: {},});</script></body>
</html>

在上面的代码中,我们通过directive方法创建了一个focus指令。

在使用该指令的时候,一定要加上v-的形式。

inserted表示的是指令的钩子函数,含义是:被绑定元素插入父节点时调用。

  相关解决方案