Vue.js自定義指令的基本使用詳情
函數(shù)式
需求1:定義一個v-big
指令,和v-text
功能類似,但會把綁定的數(shù)值放大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 //創(chuàng)建vue實例 new Vue({ el: "#root", data: { n:1 }, directives:{ /*big:function () { }*/ //big函數(shù)合適會被調用? //1、指令與函數(shù)成功綁定時(一上來) //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 //創(chuàng)建vue實例 new Vue({ el: "#root", data: { n:1 }, directives:{ fbind:{ bind(element,binding){ //指令與函數(shù)成功綁定時(一上來) 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:{ 指令名:回調函數(shù) } })
(2).全局指令
Vue.directive(指令名,配置對象)
或 Vue.directive(指令名,回調函數(shù))
二、配置對象中常用的3個回調:
- (1).bind:指令與元素成功綁定時調用
- (2).inserted:指令所在元素被插入頁面時調用
- (3).update:指令所在模板結構被重新解析時調用
三、備注:
- 1.指令定義時不加
v-
,但使用時要加v-
- 2.指令名如果是多個單詞,要使用
kebab-case
命名方式,不要用camelCase
命名
到此這篇關于Vue 自定義指令的基本使用詳情的文章就介紹到這了,更多相關Vue 自定義指令內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決vue?vite啟動項目報錯ERROR:?Unexpected?“\x88“?in?JSON?的問題
這篇文章主要介紹了vue?vite啟動項目報錯ERROR:?Unexpected?“\x88“?in?JSON?原因,本文給出出現(xiàn)此類問題的原因所在并給出解決方法,需要的朋友可以參考下2022-09-09vue router使用query和params傳參的使用和區(qū)別
本篇文章主要介紹了vue router使用query和params傳參的使用和區(qū)別,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11Vue 2.0 中依賴注入 provide/inject組合實戰(zhàn)
這篇文章主要介紹了Vue 2.0 依賴注入 provide/inject組合,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-06-06Vue?import?from省略后綴/加載文件夾的方法/實例詳解
本文介紹Vue在import時省略后綴以及import文件夾的方法,結合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08django簡單的前后端分離的數(shù)據(jù)傳輸實例 axios
這篇文章主要介紹了django簡單的前后端分離的數(shù)據(jù)傳輸實例 axios,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05