Vue/Quasar Global Helper Functions - Wed, Jul 28, 2021
Make functions/methods globally available to your Quasar or Vue project.
We will be writing helpers functions on src/plugins/helper.js
Example Usage
- JS:
this.$helper.titleCase(string)
orself.$helper.titleCase(string)
- JS:
Vue.$helper.titleCase(string)
- HTML:
<template v-if='$helper.checkRole("developer")'>
- PUG:
template(v-if='$helper.checkRole("developer") || $helper.checkRole("admin")')
NOTE
Remember to update you quasar.conf.js
plugins: [
'axios',
'helper', <---
'vuelidate'
]
src/plugins/helper.js
import {
Notify
} from 'quasar'
function titleCase (string) {
if (typeof string !== 'string') {
return new Error('Expected string as a parameter')
}
return string
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.substring(1, word.length))
.join(' ')
}
function notifySuccess (message) {
Notify.create({
color: 'green',
position: 'top',
icon: 'done',
message: message || 'Los datos se han cargado, estamos listos!',
})
}
function notifyFailure (message) {
Notify.create({
color: 'negative',
position: 'top',
icon: 'report_problem',
message: message || 'La acción ha fallado, por favor intente de nuevo'
})
}
function checkRole (role) {
const user = JSON.parse(localStorage.getItem('user'))
if (user) {
// console.log('checkRole', role, user.roles)
return Boolean(user.roles.indexOf(role) >= 0)
}
return false
}
function checkUserRole (user, role) {
if (user) {
// console.log('checkRole', role, user.roles)
return Boolean(user.roles.indexOf(role) >= 0)
}
return false
}
function onlyAdmins () {
return checkRole('developer') || checkRole('admin')
}
// leave the export, even if you don't use it
export default ({ app, router, Vue }) => {
Vue.prototype.$helper = {
titleCase,
notifySuccess,
notifyFailure,
checkRole,
checkUserRole,
onlyAdmins
}
}