您的位置:首页 > 产品设计 > UI/UE

vue自定义指令

2017-02-21 21:46 323 查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
body, p, img, dl, dt, dd, ul, ol, h1, h2, h3, h4, h5, h6 { margin: 0; padding: 0; }
body { position: relative; font: 12px/1.5 Simsun, Arial; }
ul, ol { list-style: none; }
img { border: 0 none; }
input, select { vertical-align: middle; }
table { border-collapse: collapse; }
s, em, i { font-style: normal; text-decoration: none; }
a { outline: none; text-decoration: none; }
a:hover { text-decoration: underline; }
.clear { *zoom: 1; }
.clear:after { clear: both; content: "."; display: block; height: 0; overflow: hidden; visibility: hidden; zoom: 1; }
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.1/lodash.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>

<div id="app">
<input v-focus="1+1" v-focusss/>
</div>

<script type="text/javascript">
Vue.directive('focus', {
bind: function () {
console.log('bind')
},
inserted: function (el, binding, vnode, oldVnode) {
console.log('inserted')
console.log(el, binding, vnode, oldVnode)
el.focus()
},
update: function () {
console.log('update')
},
componentUpdated: function () {
console.log('componentUpdated')
},
unbind: function () {
console.log('unbind')
}
})

Vue.directive('focusss', {
inserted: function (el) {
el.blur()
}
})

var v = new Vue({
el: '#app'
})
</script>
</body>
</html>


使用指令方法Vue.directive,创建自定义指令,第一个参数为自定义指令的名称,第二个参数为一个对象。

这个对象里可以设置一些钩子函数,比如bind,inserted,update,componentUpdated,unbind

函数对应一些参数,如el,binding,vnode,oldVnode等,

然后在节点上设置该自定义指令v-*** 即可

如果只需要bind和update钩子,函数也可以简写成下列形式:

Vue.directive('color-swatch', function (el, binding) {
el.style.backgroundColor = binding.value
})


也可以传入对象字面量

<div v-demo="{ color: 'white', text: 'hello!' }"></div>


Vue.directive('demo', function (el, binding) {
console.log(binding.value.color) // => "white"
console.log(binding.value.text)  // => "hello!"
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: