Vue.directive("事件名称",内容),这样写比较抽象,看下面内容:
事件名称不需要加“v-”,Vue会自动添加,使用时需要带上v-。
html:
搜索:<input type="text" class="form-control" v-focus>
Js:
Vue.directive("focus", {
bind: function (el) {
//bind:当指令绑定到元素上时自动调用这个函数,只会触发一次。第一个参数是el,表示绑定的元素,
// 是一个原生js对象,由于绑定时只在内存中,并未加入到dom中,所以不能进行dom操作,如focus。
},
inserted: function (el) {//inserted:表示元素插入到DOM时会执行inserted函数,只会触发一次。
el.focus()
},
updated: function () {//当Vnode更新的时候触发updated,可以触发多次。
}
})
效果:在访问页面时自动获取了焦点。
注意事项:bind与inserted均只能生效一次,且在inserted之前进行DOM操作无效, 比如进行focus操作。