使用vue的自定义指令来整合某个重复使用的底层操作
举个聚焦输入框的例子,如下:
当页面加载时,该元素将获得焦点 (注意:autofocus 在移动版 Safari 上不工作)。事实上,只要你在打开这个页面后还没点击过任何内容,这个输入框就应当还是处于聚焦状态。现在让我们用指令来实现这个功能:
// 在main.js中注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
// 当被绑定的元素插入到 DOM 中时……
inserted: function (el) {
// 聚焦元素
el.focus()
}
})
如果想注册局部指令,组件中也接受一个 directives 的选项:
directives: {
focus: {
// 指令的定义
inserted: function (el) {
el.focus()
}
}
}
然后你可以在模板中任何元素上使用新的 v-focus property,如下:
<input v-focus>
另外一个例子:
全局a标签需要href参数来实现鼠标跳转路由,如果有很多标签的href的路由一样,参数不同,则可以使用自定义指令:
// bindling 中存的是a标签传来的值,可以是对象
Vue.directive('to-where', function(el, binding) {
const id = Base64.encode(binding.value.id)
el.href = '/xxx/xxx/xxx?id=' + id
})
<a v-to-where="{id: yourId}" /> // to-where就是指令的名称
另外,如果想禁止dom的原生属性,例如a标签跳转路由后会刷新页面,使用vue的prevent属性,在click中增加
<a v-to-where="{id: yourId}" @click.prvent="yourFunction" />