首先要理解 自定义指令directives和自定义组件component的区别
组件就像一个英雄,指令就像英雄的技能,一个英雄可以有多个技能,一个技能也可以被多个英雄拥有
在实际开发自定义指令的使用分为三步
1.创建GlobalDirective.vue 作为自定义指令 的独立模块
指定一般有两个参数
参数1:为指令所在的元素节点
参数2:用 b.vlaue来获取指令绑定的值 用b.modifiers来获取一个对象,为指令的修饰符内容
内容格式如下
<script>
function focus(el) {
el.focus()
}
function pin(el, b) {
var mo = b.modifiers;
if(b.value) {
el.style.position = 'fixed';
for(var item in mo) {
if(mo[item]) {
el.style[item] = '10px';
}
}
} else {
el.style.position = 'static';
}
}
export default {//必须输出要用的自定义指令
focus,
pin
}
</script>
2.在main.js引入 自定义事件模块 并解析
必须在vue实例化之前引入并循环解析为全局自定义指令
import Directives from './GlobalDirective'
Object.keys(Directives).forEach(key => {
Vue.directive(key, Directives[key])
})
3.在其他组件用任意调用
<template>
<div class="Directive">
<h1>自定义指令</h1>
<input type="text" v-focus/>
</div>
</template>