Vue.js自定义指令的基本使用详情
函数式
需求1:定义一个v-big
指令,和v-text
功能类似,但会把绑定的数值放大10倍
<div id="root"> <h2>当前的n值是<span v-text="n"></span></h2> <h2>放大10倍后的n值是:<span v-big="n"></span></h2> <button @click="n++">点我n+1</button> </div>
<script type="text/javascript"> Vue.config.productionTip = false //创建vue实例 new Vue({ el: "#root", data: { n:1 }, directives:{ /*big:function () { }*/ //big函数合适会被调用? //1、指令与函数成功绑定时(一上来) //2、指令所在的模板被重新解析时 big(element,binding){ element.innerHTML = binding.value * 10 } } }) </script>
对象式
需求2:定义一个v-fbind
指令,和v-bind
功能类似,但可以让其所绑定的input
元素默认获取焦点
<div id="root"> <input type="text" v-bind:value="n"><br/> <input type="text" v-fbind:value="n"><br/> <button @click="n++">点我n+1</button> </div>
<script type="text/javascript"> Vue.config.productionTip = false //创建vue实例 new Vue({ el: "#root", data: { n:1 }, directives:{ fbind:{ bind(element,binding){ //指令与函数成功绑定时(一上来) console.log("bind"); element.value = binding.value }, inserted(element,binding){ //指令所在元素被插入页面时 console.log("inserted"); element.focus() }, update(element,binding){ //指令所在元素被重新解析时 console.log("update"); element.value = binding.value } } } }) </script>
使用时的一些坑
命名 如果指令是多个单词:
<h2>放大10倍后的n值是:<span v-big-number="n"></span></h2>
那么需要这样写:
'big-number':function (element,binding){ element.innerHTML = binding.value * 10 }
或者:
'big-number' (element,binding){ element.innerHTML = binding.value * 10 }
this
directives:{ fbind:{ bind(element,binding){ //此处的this是window console.log("bind"); element.value = binding.value } } }
全局指令:
像过滤器一样,我们把刚才的两个指令改为全局指令
Vue.directive('big', function (element, binding) { element.innerHTML = binding.value * 10 })
Vue.directive('fbind',{ bind(element,binding){ element.value = binding.value }, inserted(element,binding){ element.focus() }, update(element,binding){ element.value = binding.value } })
总结
一、定义语法:
(1).局部指令
new Vue({ directives:{ 指令名:配置对象 } })
或:
new Vue({ directives:{ 指令名:回调函数 } })
(2).全局指令
Vue.directive(指令名,配置对象)
或 Vue.directive(指令名,回调函数)
二、配置对象中常用的3个回调:
- (1).bind:指令与元素成功绑定时调用
- (2).inserted:指令所在元素被插入页面时调用
- (3).update:指令所在模板结构被重新解析时调用
三、备注:
- 1.指令定义时不加
v-
,但使用时要加v-
- 2.指令名如果是多个单词,要使用
kebab-case
命名方式,不要用camelCase
命名
到此这篇关于Vue 自定义指令的基本使用详情的文章就介绍到这了,更多相关Vue 自定义指令内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
解决vue vite启动项目报错ERROR: Unexpected “\x88“ in JSON 的问题
这篇文章主要介绍了vue vite启动项目报错ERROR: Unexpected “\x88“ in JSON 原因,本文给出出现此类问题的原因所在并给出解决方法,需要的朋友可以参考下2022-09-09vue router使用query和params传参的使用和区别
本篇文章主要介绍了vue router使用query和params传参的使用和区别,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-11-11Vue 2.0 中依赖注入 provide/inject组合实战
这篇文章主要介绍了Vue 2.0 依赖注入 provide/inject组合,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值 ,需要的朋友可以参考下2019-06-06Vue import from省略后缀/加载文件夹的方法/实例详解
本文介绍Vue在import时省略后缀以及import文件夹的方法,结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-08-08
最新评论