按钮添加防重复点击
前端项目中,表单提交时,为了防止用户点击多次,一般都需要对按钮进行防重复点击处理。全局配置按钮节流指令 v-preventClick,实现防重复点击。
1、新建 plugin.js
const plugin = {
install(Vue, options) {
// 防止按钮重复点击,通过全局指令实现,按钮添加指令 v-preventClick
Vue.directive('preventClick', {
inserted(el, binding) {
el.addEventListener('click', () => {
if(!el.disabled) {
el.disabled = true
setTimeout(() => {
el.disabled = false
}, binding.value || 1500)
}
})
}
})
}
}
export default plugin
2、main.js中引入封装插件plugin,并注册
import plugin from './utils/plugin.js'
Vue.use(plugin)
了解:vue 全局注册插件
Vue.use(plugin)
ue.use() 的作用是全局注册插件
如果插件是一个对象,必须提供 install 方法;如果插件是一个函数,会被作为install方法
install 的第一个参数是vue的实例
Vue.use() 需要在调用 new Vue() 之前被调用
插件功能范围
plugin.install = function (Vue, options) {
// 1. 添加全局方法或 property
Vue.myGlobalMethod = function () {
// 逻辑...
}
// 2. 添加全局资源(指令/过滤器/过渡等)
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 逻辑...
}
...
})
// 3. 注入组件选项
Vue.mixin({
created: function () {
// 逻辑...
}
...
})
// 4. 添加实例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 逻辑...
}
}
了解: 自定义指令
自定义指令分类
私有自定义指令:组件中 directives 对象下注册的指令,只能在当前组件使用 (directives: { 指令名: {} })
全局自定义指令:main.js中 通过Vue.directive(指令名, 对象)声明的指令,全局可用
指令常用生命周期函数
bind:当指令绑定在标签上时触发的函数(此时标签还没有挂载到父元素上,DOM还未绘制)
inserted:当绑定指令的元素 插入到 父节点时触发的函数(可以获取父元素,操作父元素,DOM绘制完成)
update:页面数据更新时触发的函数
语法
私有自定义指令
directives: {
color: {
// el - 绑定的指令的 dom元素本身
// binding - 指令的相关数据,可以随意命名,binding.value可以取到指令绑定的值
bind(el, binding) {
el.style.color = binding.value
}
}
}
// 指令使用:v-color="red"
全局自定义指令
Vue.directive('color', {
bind(el, binding) {
},
inserted(el, binding) {
}
})