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时执行
图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