本文摘自PHP中文网,作者php中世界最好的语言,侵删。
这次给大家带来Vue.directive()的图文详解,使用Vue.directive()的注意事项有哪些,下面就是实战案例,一起来看一下。官网实例:
https://cn.vuejs.org/v2/api/#Vue-directive
https://cn.vuejs.org/v2/guide/custom-directive.html
指令定义函数提供了几个钩子函数(可选):
bind: 只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个在绑定时执行一次的初始化动作。
inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。
update: 被绑定元素所在的模板更新时调用,而不论绑定值是否变化。通过比较更新前后的绑定值,可以忽略不必要的模板更新(详细的钩子函数参数见下)。
componentUpdated: 被绑定元素所在模板完成一次更新周期时调用。
unbind: 只调用一次, 指令与元素解绑时调用。
本人菜鸟型,看官网蒙圈,然后百度Vue.directive()
的实例和用法,有的很高深,有的不健全,我贴上两个简单的demo,希望对看到的朋友有帮助:
1、官网给出的demo,刷新页面input自动获取焦点:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <p id= "app" >
<SPAN style= "WHITE-SPACE: pre" > </SPAN><input type= "text" v-focus/>
</p>
<p id= "app" >
<input type= "text" v-focus/>
</p>
Vue.directive( 'focus' , {
inserted: function (el,binding) {
<SPAN style= "WHITE-SPACE: pre" > </SPAN>
<SPAN style= "WHITE-SPACE: pre" > </SPAN>el.focus();
}
});
new Vue({
el: '#app'
});
Vue.directive( 'focus' , {
inserted: function (el,binding) {
el.focus();
}
});
new Vue({
el: '#app'
});
|
2、一个拖拽的demo: 1)被拖拽的元素必须用position定位,才能被拖动;
2)自定义指令完成后需要实例化Vue,挂载元素;
3)inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | <style type= "text/css" >
.one,.two{
height:100px;
width:100px;
border:1px solid #000;
position: absolute;
-webkit-user-select: none;
-ms-user-select: none;
-moz-user-select: -moz-none;
cursor: pointer;
}
.two{
left:200px;
}
</style>
<p id= "app" >
<p class = "one" v-drag>拖拽one</p>
<p class = "two" v-drag>拖拽two</p>
</p>
<style type= "text/css" >
.one,.two{
height:100px;
width:100px;
border:1px solid #000;
position: absolute;
-webkit-user-select: none;
-ms-user-select: none;
-moz-user-select: -moz-none;
cursor: pointer;
}
.two{
left:200px;
}
</style>
<p id= "app" >
<p class = "one" v-drag>拖拽one</p>
<p class = "two" v-drag>拖拽two</p>
</p>
[javascript] view plain copy print ?Vue.directive( 'drag' , {
inserted: function (el){
el.onmousedown= function (e){
let l=e.clientX-el.offsetLeft;
let t=e.clientY-el.offsetTop;
document.onmousemove= function (e){
el.style.left=e.clientX-l+ 'px' ;
el.style.top=e.clientY-t+ 'px' ;
};
el.onmouseup= function (){
document.onmousemove=null;
el.onmouseup=null;
}
}
}
})
new Vue({
el: '#app'
});
|
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
使用H5做出添加禁止缩放
ionic2中怎么使用自动生成器
以上就是Vue.directive()的图文详解的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
html基础图像知识详解
phonegap实现提示操作详解
h5的服务器推送事件详解
Vue.directive()的图文详解
html怎样实现图文混排
js || &&详解
dw文本框制作步骤详解
html2canvas把div保存图片高清图(图文教程)
phonegap操作数据库详解
h5的标签使用详解
更多相关阅读请进入《Vue.directive》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » Vue.directive()的图文详解