温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Vue项目中使用directive()函数

发布时间:2021-01-12 15:08:12 来源:亿速云 阅读:127 作者:Leah 栏目:web开发

本篇文章为大家展示了如何在Vue项目中使用directive()函数,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

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

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

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

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

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

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

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

<div id="app"> 
<SPAN > </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 > </SPAN>// 聚焦元素  
    <SPAN > </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()函数,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI