首先,Vue.directive要在实例初始化以前,否则会报错,还有,定义的指令不支持驼峰式写法,也会报下面一样的错,虽然在源码中没有找到在哪里统一处理大小写,可是在有关directive的方法中捕捉到的指令命名统一变为小写,因此,仍是用'-'或者'_'分割吧。javascript
vue.js:491 [Vue warn]: Failed to resolve directive: xxx
而后,其定义方式有两种,一种是Vue.directive('xxx', function(el, bind, vNode){}),其中el为dom,vNode为vue的虚拟dom,bind为一较复杂对象,详情可见Vue-directive钩子函数中的参数的参数,还有一种,为html
Vue.directive('my-directive', { bind: function () {}, inserted: function () {}, update: function () {}, componentUpdated: function () {}, unbind: function () {} })
参数表明的含义,参见钩子函数描述vue
最后,要使用自定义的指令,只需在对用的元素中,加上'v-'的前缀造成相似于内部指令'v-if','v-text'的形式。java
// Vue.directive Vue.directive('test_directive', function(el, bind, vNode){ el.style.color = bind.value; }); var app = new Vue({ el: '#app', data: { num: 10, color: 'red' }, methods: { add: function(){ this.num++; } } });
固然,也能够将method中的方法加入,bind.value即为methods中的方法。app
<div id="app"> <div v-test_directive="changeColor">{{num}}</div> <button @click="add">增长</button> </div> <script type="text/javascript"> // Vue.directive Vue.directive('test_directive', function(el, bind, vNode){ el.style.color = bind.value(); }); var app = new Vue({ el: '#app', data: { num: 10, color: 'red' }, methods: { add: function(){ this.num++; }, changeColor: function(){ return this.color; } } });
这种形式,能够模仿'v-once',并进行必定的复杂逻辑,可是想要彻底达到'v-once',可能须要考虑Vue-directive的钩子函数各个周期。下面是固定num的值,使得add的方法无效。dom
<div id="app"> <div v-test_directive="changeColor">{{num}}</div> <button @click="add">增长</button> </div> <script type="text/javascript"> // Vue.directive Vue.directive('test_directive', function(el, bind, vNode){ el.style.color = bind.value(); }); var app = new Vue({ el: '#app', data: { num: 10, color: 'red' }, methods: { add: function(){ this.num++; }, changeColor: function(){ this.num = 20; return this.color; } } });