定义一个检测授权的指令
指令的作用:如果元素加了该指令,元素被点击是会检测,当前点击的用户有权限执行之后的逻辑
封装指令 /directives/auth.js
import store from '@/store'
const auth = {
inserted(el, binding) {
el.onmousedown = (event) => {
event.preventDefault()
//这里我们检测这个是否已经登录,这里只是简单的做个示例
if (!store.state.user.userId) {
store.commit('Login', false)
}
}
}
}
export default auth
多指令注入 /directives/index.js
为了方便一次注入多个指令,我们选择使用插件形式,全局注册多个指令
import auth from './auth'
// 自定义指令
const directives = {
auth
}
export default {
install(Vue) {
Object.keys(directives).forEach((key) => {
Vue.directive(key, directives[key])
})
}
}
使用插件 main.js
import Directives from '@/directives'
Vue.use(Directives)