Custom Directives in Vue

1 什么情况下需要使用指令?

需要和 DOM elements 交互,就是封装一些小的指令在DOM element上

 

2 Vue都提供哪些指令形式?

  • v-example
  • v-example="value"  // 传值
  • <div v-if="stateExample">I will show up if stateExample is true</div>
  • v-example="'string'" // string 作为表达式传过去
  • <p v-html="'<strong>this is an example of a string in some text</strong>'"></p>
  • v-example:arg="value" // 传参
  • <div v-bind:class="someClassObject"></div>

    v-example:arg.modifier="value" //使用modifier

  • <button v-on:submit.prevent="onSubmit"></button>

     

3 如何自定义指令?

Vue.directive('tack');

使用

<p v-tack>This element has a directive on it</p>

hooks:

  • bind: 当指令和element绑定在一起时开始执行
  • inserted: 当element 插入到父DOM中开始执行
  • update: 当element更新时执行
  • componentUpdated: 当element和children更新时执行
  • unbind: 当指令被removed时执行

114637_BEQB_2510955.png

图1 hook解析

el: 指令绑定的element

binding: 包含了传到hook的参数的对象,比如name, value, oldValue, expression, arg 和 modifiers  只读

vnode: 在virtual DOM中可以引用的node,只读

 

4 示例

  • 简单

App.vue

<p v-tack>I will now be tacked onto the page</p>

main.js

Vue.directive('tack', {
  bind(el, binding, vnode) {
    el.style.position='fixed'
  }
});

 

  • 来个传值的

App.vue

 <p v-tack="70">Stick me 70px from the top of the page</p>

main.js

Vue.directive('tack', {
  bind(el, binding, vnode) {
    el.style.position = 'fixed'
    el.style.top = binding.value + 'px'  // 使用了binding.value
  }
});

 

  • 试试传参

App.vue

<p v-tack:left="70">I'll now be offset from the left instead of the top</p>

main.js

Vue.directive('tack', {
  bind(el, binding, vnode) {
    el.style.position = 'fixed'
    const s = (binding.arg === 'left' ? 'left' : 'top') // 判断 binding.arg
    el.style[s] = binding.value + 'px'
  }
});

 

  • 我想自由地传值

App.vue

 <p v-tack="{top: '40', left: '100'}">Stick me 40px from the top of the page and 100px from the left of the page</p>

main.js

Vue.directive('tack', {
  bind(el, binding, vnode) {
    el.style.position = 'fixed'
    el.style.top = binding.value.top + 'px'  // 使用 value.top
    el.style.left = binding.value.left + 'px' // 使用 value.left 
  }
});

 

参考资料:https://css-tricks.com/power-custom-directives-vue/?utm_source=javascriptweekly&utm_medium=email

 

转载于:https://my.oschina.net/u/2510955/blog/895840

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值