vue.js 自定义指令
钩子函数:
bind
inserted
update
componentUpdated
unbind
钩子函数完整实例:
html:
<div id="hook-arguments-example" v-demo:hello.a.b="message" v-color-swatch="bgColor" ></div>
js:
Vue.directive('demo', { bind: function (el, binding, vnode) { var s = JSON.stringify; // 用于从一个对象解析出字符串 el.innerHTML = 'name: ' + s(binding.name) + '<br>' +'value: ' + s(binding.value) + '<br>' +'expression: ' + s(binding.expression) + '<br>' +'argument: ' + s(binding.arg) + '<br>' +'modifiers: ' + s(binding.modifiers) + '<br>' + 'vnode keys: ' + Object.keys(vnode).join(', ') } }); Vue.directive('color-swatch', function (el, binding) { el.style.backgroundColor = binding.value; }); new Vue({ el: '#hook-arguments-example', data: { message: 'hello!', bgColor: 'red' } });
结果:
Vue混合:
// 定义一个混合对象 var mixin = { methods: { foo: function () { console.log('foo'); }, conflicting: function () { console.log('from mixin'); } } }; var vm = new Vue({ mixins: [mixin], methods: { bar: function () { console.log('bar'); }, conflicting: function () { console.log('from self'); } } }); vm.foo(); vm.bar(); vm.conflicting();