当前位置: 移动技术网 > IT编程>脚本编程>vue.js > Vue.directive()的用法和实例详解

Vue.directive()的用法和实例详解

2018年03月08日  | 移动技术网IT编程  | 我要评论
官网实例: https://cn.vuejs.org/v2/api/#vue-directive 指令定义函数提供了几个钩子函数(可选): bind: 只调用

官网实例:

https://cn.vuejs.org/v2/api/#vue-directive

指令定义函数提供了几个钩子函数(可选):

bind: 只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个在绑定时执行一次的初始化动作。
inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。

update: 被绑定元素所在的模板更新时调用,而不论绑定值是否变化。通过比较更新前后的绑定值,可以忽略不必要的模板更新(详细的钩子函数参数见下)。

componentupdated: 被绑定元素所在模板完成一次更新周期时调用。

unbind: 只调用一次, 指令与元素解绑时调用。

本人菜鸟型,看官网蒙圈,然后百度vue.directive()的实例和用法,有的很高深,有的不健全,我贴上两个简单的demo,希望对看到的朋友有帮助:

1、官网给出的demo,刷新页面input自动获取焦点:

<div id="app"> 
<span style="white-space: pre"> </span><input type="text" v-focus/> 
</div> 

<div id="app">
 <input type="text" v-focus/>
</div>

// 注册一个全局自定义指令 v-focus  
vue.directive('focus', { 
  // 当绑定元素插入到 dom 中。  
  inserted: function (el,binding) { 
    <span style="white-space: pre"> </span>// 聚焦元素  
    <span style="white-space: pre"> </span>el.focus(); 
  } 
}); 
new vue({ 
  el:'#app' 
}); 
// 注册一个全局自定义指令 v-focus
vue.directive('focus', {
  // 当绑定元素插入到 dom 中。
  inserted: function (el,binding) {
   // 聚焦元素
   el.focus();
 }
});
new vue({
  el:'#app'
});

2、一个拖拽的demo: 1)被拖拽的元素必须用position定位,才能被拖动;

2)自定义指令完成后需要实例化vue,挂载元素;

3)inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。

<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> 
<div id="app"> 
  <div class="one" v-drag>拖拽one</div> 
  <div class="two" v-drag>拖拽two</div> 
</div> 
<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>
<div id="app">
 <div class="one" v-drag>拖拽one</div>
 <div class="two" v-drag>拖拽two</div>
</div>
[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' 
}); 

总结

以上所述是小编给大家介绍的vue.directive()的用法和实例详解,希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网