2π
I am going to show you how to do it supporting lazy loading too.
//this function will do the check and import the component supporting lazy loading
//if the check does not fulfilled then the component will not imported
function check_condition(name_component) {
if (name_component === 'Project') {
const user = store.state.user
if (user.current_role == 'admin' || user.current_role == 'owner') {
return () => import(`@/components/${name_component}.vue`)
}
return
}
return () => import(`@/components/${name_component}.vue`)
}
export default new Router({
routes: [
{
path: '/',
name: 'home',
components: {
default: check_condition('Home'),
project: check_condition('Project')
}
},
{
path: '/about',
name: 'about',
component: check_condition('About')
}
]
})
I like the above approach.Though of course there are also other ways.
If you donβt like the above or it does not fit with your problem you can try the below approach.
Say you have is vuex store state:
state: { user: 'admin' //or visitor }
And you want to show the settings_button
component when the user is admin
but not when is visitor
:
computed: {
should_show_settings_button () {
return this.$store.state.user === 'admin'
}
}
<template v-if="should_show_settings_button">
<router-view name="settings_button"></router-view>
</template>
π€Roland
- [Vuejs]-Error: Error: the "filename" option is required to use includes and extends with "relative" paths
- [Vuejs]-How to validate a condition when a status changes in vuejs
0π
You can simply check to
url:
beforeRouteEnter (to, from, next) {
if(to.pathname !== '/') {
//yours check
}
else {
next();
}
}
Or more complex way is to everytime check array of your routes. You can check by a component name then.
let routesObjects = routes.reduce((obj, route) => { obj[route.path] = route.name; return obj; }, {});
beforeRouteEnter (to, from, next) {
let path = to.pathname;
if(routesObjects.hasOwnProperty(to) && routesObjects[to] !== 'home') {
//yours check
}
else {
next();
}
}
In case if u have 2 components with the same pathnam
u could combine a beforeEach
hook and meta
Setup meta
tag in your component
routes: [
{ name: 'home', path: '/', meta: { isHome: true } }
]
Then just check it
router.beforeEach((to, from, next) => {
if(to.meta.isHome !== undefined && to.meta.isHome) { next(); }
else { //your check }
})
π€GONG
Source:stackexchange.com