Vue自定义指令
自定义指令
全局指令:使用Vue.directive(‘指令名’,fn({}))定义全局指令。
局部指令:使用directives:{}定义局部指令。
自定义指令-颜色
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> </head> <body> <div id="app"> <p v-color="'red'">hello Word</p> </div> <script src="./color.js"></script> </body> </html>
const app = new Vue({ el: '#app', directives: { 'color': function (el, binding, vnode) { console.log(el); console.log(binding); console.log(vnode); el.style.color = binding.value }, } })
自定义指令-表单
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> </head> <body> <div id="app"> <input type="text" v-form.lazy.trim.upper="name"> </div> <script src="./form.js"></script> </body> </html>
Vue.directive('form',{
bind(el,binding, vnode){
console.log(el);
console.log(binding);
console.log(vnode);
const {context} = vnode
const {expression,modifiers} = binding
const {lazy, trim, number, upeer} = modifiers
el.value = context[expression]
el.addEventListener(lazy?'blur':'input',function(e){
let val = e.target.value
if(trim) val = val.trim()
if(number) val = val.number(val)
if(upeer) val = val.toUpperCase()
context[expression] = val
})
},
update(el,binding,vnode){
el.value = vnode.context[binding.expression]
}
})
const app = new Vue({
el:'#app',
data:{
name:''
}
})
自定义指令-聚焦
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> </head> <body> <div id="app"> <input type="text" v-focus> </div>
<script src="jurisdiction.js"></script>
</body> </html>
// 注册一个全局自定义指令 `v-focus` Vue.directive('focus', { // 当被绑定的元素插入到 DOM 中时…… inserted: function (el) { // 聚焦元素 el.focus() } }) new Vue({ el: '#app' })

浙公网安备 33010602011771号