博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Custom Directives in Vue
阅读量:7183 次
发布时间:2019-06-29

本文共 1741 字,大约阅读时间需要 5 分钟。

hot3.png

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

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

 

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

  • v-example
  • v-example="value"  // 传值
  • I will show up if stateExample is true
  • v-example="'string'" // string 作为表达式传过去
  • v-example:arg="value" // 传参
  • v-example:arg.modifier="value" //使用modifier

  •  

3 如何自定义指令?

Vue.directive('tack');

使用

This element has a directive on it

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

I will now be tacked onto the page

main.js

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

 

  • 来个传值的

App.vue

Stick me 70px from the top of the page

main.js

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

 

  • 试试传参

App.vue

I'll now be offset from the left instead of the top

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

Stick me 40px from the top of the page and 100px from the left of the page

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

你可能感兴趣的文章
test
查看>>
Android消息通知Totast的实现
查看>>
如何更好的管理企业内的打印机
查看>>
感慨下,什么样的IT
查看>>
SQL server 2005 PIVOT运算符的使用
查看>>
我的友情链接
查看>>
Dubbo源码分析(2),Dubbo中采用的设计模式
查看>>
我的友情链接
查看>>
LVS-DR工作原理图文详解
查看>>
PPT演讲10大准备技巧
查看>>
linux连接数检查
查看>>
水火交融-Windows上的Linux容器
查看>>
Linux调优方案,sysctl.conf的设置
查看>>
dnsmasq 小巧且方便地用于配置DNS和DHCP的工具
查看>>
日期控件
查看>>
有关缓存,缓存算法,缓存框架
查看>>
Redhat6 安装mysql
查看>>
python利用本地保存cookies文件登录调取api
查看>>
OpenSSL生成根证书CA及签发子证书
查看>>
MySql远程连接的设置问题
查看>>