Related
Using Vue3 - Vuerouter4 - Vite
I try to import the components and routes in vue router but I face this error (only for the route that has children in my paths):
my router code:
import { createRouter, createWebHistory } from "vue-router";
import paths from "./path";
import { TokenService } from "#/services/storage.services.js";
function route(options) {
let path = options.path;
let view = options.view;
let name = options.name;
let meta = options.meta ? options.meta : "";
let children = options.children ? options.children : null;
let redirect = options.redirect ? options.redirect : null;
let currentRoute = {
name: name || view,
path,
meta,
component: (resolve) => import(`#/views/${view}.vue`).then(resolve),
};
if (children && Array.isArray(children)) {
children = children.map((path) => {
path.view = view + "/" + path.view;
return path;
});
currentRoute["children"] = children.map((path) => route(path));
}
if (redirect) {
currentRoute["redirect"] = redirect;
}
return currentRoute;
}
// Create a new router
const router = createRouter({
history: createWebHistory(),
routes: paths
.map((path) => route(path))
.concat([{ path: "/:pathMatch(.*)", redirect: "admin/home" }]),
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition;
}
if (to.hash) {
return { selector: to.hash };
}
return { left: 0, top: 0 };
},
});
export default router;
my paths that are in paths.js:
export default [
{
path: "/admin",
name: "Admin",
view: "Admin",
redirect: "Admin/Home",
children: [
{
path: "Home",
name: "Home",
view: "Home",
meta: {
auth: true,
title: "داشبورد",
},
},
{
path: "TRANSACTION",
name: "TRANSACTION",
view: "Transaction",
meta: {
auth: true,
title: "تراکنش ها",
},
},
{
path: "SMS-MANAGEMENT",
name: "SMSManagement",
view: "SMSManagement",
meta: {
auth: true,
title: "مدیریت پیامک ها",
},
},
{
path: "CAR-LIST",
name: "CAR-LIST",
view: "Car-List",
meta: {
auth: true,
title: "لیست خودرو های اجاره ای",
},
},
{
path: "ADDRENTCAR",
name: "ADDRENTCAR",
view: "AddRentCar",
meta: {
auth: false,
title: "افزودن خودرو اجاره ای",
},
},
{
path: "EDITRENTCAR",
name: "EDITRENTCAR",
view: "AddRentCar",
meta: {
auth: false,
title: "ویرایش خودرو اجاره ای",
},
},
{
path: "USERS",
name: "USERS",
view: "Users",
meta: {
auth: true,
title: "لیست کاربران",
},
},
{
path: "CARS",
name: "CARS",
view: "Cars",
meta: {
auth: true,
title: "لیست خودرو ها",
},
},
{
path: "REQUESTS",
name: "REQUESTS",
view: "REQUESTS",
meta: {
auth: true,
title: "لیست درخواست ها",
},
},
],
},
{
path: "",
name: "MAIN-HOME",
view: "main-home",
meta: {
auth: true,
title: "صفحه اصلی",
public: true,
},
},
{
path: "/PROFILE",
name: "PROFILE",
view: "PROFILE",
meta: {
auth: true,
title: "پروفایل من",
},
},
{
path: "/LOGIN",
name: "LOGIN",
view: "Login",
meta: {
auth: true,
title: "ورود",
},
},
{
path: "/ALLCARS",
name: "ALLCARS",
view: "ALLCARS",
meta: {
public: true,
auth: true,
title: "لیست تمام خودرو ها",
},
},
{
path: "/ABOUTUS",
name: "ABOUTUS",
view: "ABOUTUS",
meta: {
public: true,
auth: true,
title: "درباره ما",
},
},
];
Any ideas what causes the error specifically for my admin route that has children??!!
........................................................................................................................................................................................................................................................................................................................................................................................................................................................................
I changed the "../views/" to "/src/views/" and problem solved.
Seems like using '..' wouldn't make it to the src folder!!!!!
Thank you #Mohammad Masoudi
In my Vue.js application I use a navigation drawer to display the different pages a user has access to. Pages are also only visible if the administrator has activated the related module. Therefore the unique moduleID is set for each page and children. The list is populated by filteredPages[]. This array is the result of displaying only the pages a user has access to. All available pages are stored in my original data source pages[].
To sum this up: A page is only shown if both of these conditions are true:
activatedModules[] contains the moduleID of a page and the children.
userPermissions[] contains the permissions value of a children (or page if there is no children).
My code:
export default {
data: () => ({
pages: [
{
text: 'Team', moduleID: 'm1',
children: [
{ text: 'Dashboard', route:'team/dashboard', permissions: 'p101', moduleID: 'm1-1' },
],
},
{
text: 'Planner', moduleID: 'm2',
children: [
{ text: 'Events', route:'/planner/events', permissions: 'p201', moduleID: 'm2-1' },
{ text: 'Calendar', route:'/planner/calendar', permissions: 'p202', moduleID: 'm2-2' },
],
},
{
text: 'HR', moduleID: 'm3',
children: [
{ text: 'Staff', route:'/hr/staff', permissions: 'p301', moduleID: 'm3-1' },
{ text: 'Config', route:'/hr/config', permissions: 'p302', moduleID: 'm3-2' },
],
},
{
text: 'Admin', moduleID: 'm4',
children: [
{ text: 'Users', route:'/admin/users', permissions: 'p401', moduleID: 'm4-1' },
{ text: 'Security', route:'/admin/security', permissions: 'p402', moduleID: 'm4-2' },
],
},
{ text: 'Support', route:'/support', permissions: 'p50', moduleID: 'm5' },
],
activatedModules: ['m1', 'm1-1', 'm3', 'm3-1', 'm3-2' 'm4', 'm4-1', 'm4-2', 'm5'],
userPermissions: ['p101', 'p301', 'p302', 'p402', 'p50'],
// This is the source for my navigation drawer:
filteredPages: []
}),
computed: {
filterArray() {
// I tried to use filter() but how can I solve the rest?
this.filteredPages = this.pages.filter(function(item) {
for (var this.activatedModules in filter) {
if /* I would assume that I have to write the condition here */
return false;
}
return true;
})
}
}
}
For the code above this should be the output:
filteredPages: [
{
text: 'Team', moduleID: 'm1',
children: [
{ text: 'Dashboard', route:'team/dashboard', permissions: 'p', moduleID: 'm1-1' },
],
},
// Notice that 'm2' is missing here because it is not in activatedModules[]
{
text: 'HR', moduleID: 'm3',
children: [
{ text: 'Staff', route:'/hr/staff', permissions: 'p301', moduleID: 'm3-1' },
{ text: 'Config', route:'/hr/config', permissions: 'p302', moduleID: 'm3-2' },
],
},
{
text: 'Admin', moduleID: 'm4',
children: [
// 'm4-1' is in activatedModules[] but the user doesn't have the permission 'p401' to view this
{ text: 'Security', route:'/admin/security', permissions: 'p402', moduleID: 'm4-2' },
],
},
{ text: 'Support', route:'/support', permissions: 'p50', moduleID: 'm5' },
]
The permissions of a user are stored in Firebase Cloud Firestore like this:
Can you help with the filtering of the array?
This should do it:
computed: {
filteredPages() {
return this.pages.map(page => ({
...page,
children: page.children
// when children is truthy
? page.children.filter(
// filter out those not in `userPermissions`
child => this.userPermissions.includes(child.permissions)
// and those not in `activatedModules`
&& this.activatedModules.includes(child.moduleID)
)
: page.children
})).filter(
// only keep page if in `activatedModules` and...
page => (this.activatedModules.includes(page.moduleID)) &&
// if children is truthy and has length or...
(page.children?.length || (
// if children is falsy and page.permissions in userPermissions
!page.children && this.userPermissions.includes(page.permissions)
))
);
}
}
See it working:
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#app',
data: () => ({
pages: [
{
text: 'Team',
moduleID: 'm1',
children: [
{ text: 'Dashboard', route:'team/dashboard', permissions: 'p101', moduleID: 'm1-1' }
],
}, {
text: 'Planner',
moduleID: 'm2',
children: [
{ text: 'Events', route:'/planner/events', permissions: 'p201', moduleID: 'm2-1' },
{ text: 'Calendar', route:'/planner/calendar', permissions: 'p202', moduleID: 'm2-2' },
],
}, {
text: 'HR',
moduleID: 'm3',
children: [
{ text: 'Staff', route:'/hr/staff', permissions: 'p301', moduleID: 'm3-1' },
{ text: 'Config', route:'/hr/config', permissions: 'p302', moduleID: 'm3-2' },
],
}, {
text: 'Admin',
moduleID: 'm4',
children: [
{ text: 'Users', route:'/admin/users', permissions: 'p401', moduleID: 'm4-1' },
{ text: 'Security', route:'/admin/security', permissions: 'p402', moduleID: 'm4-2' },
],
},
{ text: 'Support', route:'/support', permissions: 'p50', moduleID: 'm5' }
],
activatedModules: ['m1', 'm1-1', 'm3', 'm3-1', 'm3-2', 'm4', 'm4-1', 'm4-2', 'm5'],
userPermissions: ['p101', 'p301', 'p302', 'p402', 'p50']
}),
computed: {
filteredPages() {
return this.pages.map(page => ({
...page,
children: page.children
? page.children.filter(
child => this.userPermissions.includes(child.permissions)
&& this.activatedModules.includes(child.moduleID)
)
: page.children
})).filter(
page => (this.activatedModules.includes(page.moduleID))
&& (page.children?.length || (
!page.children && this.userPermissions.includes(page.permissions)
))
);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<pre v-html="filteredPages" />
</div>
in the code snippet below I used a filter first to filter by activatedModules then used a forEach to filter each object children property by userPermissions, I think you can implement this in your vue component or get an idea about how to tackle the problem (hope this helps):
const pages = [{
text: 'Team',
moduleID: 'm1',
children: [{
text: 'Dashboard',
route: 'team/dashboard',
permissions: 'p1382',
moduleID: 'm1-1'
}, ],
},
{
text: 'Planner',
moduleID: 'm2',
children: [{
text: 'Events',
route: '/planner/events',
permissions: 'p47289',
moduleID: 'm2-1'
},
{
text: 'Calendar',
route: '/planner/calendar',
permissions: 'p283',
moduleID: 'm2-2'
},
],
},
{
text: 'HR',
moduleID: 'm3',
children: [{
text: 'Staff',
route: '/hr/staff',
permissions: 'p34729',
moduleID: 'm3-1'
},
{
text: 'Config',
route: '/hr/config',
permissions: 'p382',
moduleID: 'm3-2'
},
],
},
{
text: 'Admin',
moduleID: 'm4',
children: [{
text: 'Users',
route: '/admin/users',
permissions: 'p3z4',
moduleID: 'm4-1'
},
{
text: 'Security',
route: '/admin/security',
permissions: 'p2u3',
moduleID: 'm4-2'
},
],
},
{
text: 'Support',
route: '/support',
permissions: 'p332j',
moduleID: 'm5'
},
];
const activatedModules = ['m1', 'm3', 'm4', 'm5'];
const userPermissions = ['m1-1', 'm3-1', 'm3-2', 'm4-2'];
// This is the source for my navigation drawer:
let filteredPages = null;
filteredPages = pages.filter(x => activatedModules.includes(x.moduleID));
filteredPages.forEach(x => {
if (x.children)
x.children = x.children.filter(y => userPermissions.includes(y.moduleID));
});
console.log(filteredPages);
Some remarks:
You should not be using function for callbacks, like you started doing for filter, as that will make you lose the right this value. Use arrow functions.
filter cannot do the job on its own, as you need to also generate new objects which may have fewer children. So you should first map to make those narrowed down objects, and then filter.
Without using Vue, you can run the following snippet, which just hard-codes the call to filterArray:
let app = {
computed: {
filterArray() {
this.filteredPages = this.pages.map(item => {
let children = (item.children || []).filter(child =>
this.activatedModules.includes(child.moduleID) &&
this.userPermissions.includes(child.permissions)
);
return (children.length || !item.children)
&& this.activatedModules.includes(item.moduleID)
&& {...item, children};
}).filter(Boolean);
}
},
data: () => ({
pages: [
{
text: 'Team', moduleID: 'm1',
children: [
{ text: 'Dashboard', route:'team/dashboard', permissions: 'p101', moduleID: 'm1-1' },
],
},
{
text: 'Planner', moduleID: 'm2',
children: [
{ text: 'Events', route:'/planner/events', permissions: 'p201', moduleID: 'm2-1' },
{ text: 'Calendar', route:'/planner/calendar', permissions: 'p202', moduleID: 'm2-2' },
],
},
{
text: 'HR', moduleID: 'm3',
children: [
{ text: 'Staff', route:'/hr/staff', permissions: 'p301', moduleID: 'm3-1' },
{ text: 'Config', route:'/hr/config', permissions: 'p302', moduleID: 'm3-2' },
],
},
{
text: 'Admin', moduleID: 'm4',
children: [
{ text: 'Users', route:'/admin/users', permissions: 'p401', moduleID: 'm4-1' },
{ text: 'Security', route:'/admin/security', permissions: 'p402', moduleID: 'm4-2' },
],
},
{ text: 'Support', route:'/support', permissions: 'p50', moduleID: 'm5' },
],
activatedModules: ['m1', 'm1-1', 'm3', 'm3-1', 'm3-2', 'm4', 'm4-1', 'm4-2', 'm5'],
userPermissions: ['p101', 'p301', 'p302', 'p402', 'p50'],
filteredPages: []
}),
};
// Demo, simulate Vue's call to computed.filterArray
let data = app.data();
app.computed.filterArray.call(data);
// Verify output:
console.log(data.filteredPages);
I am trying to test if the logged in user has the appropriate role to see certain items in the dashboard.
I have an array of objects. These are the items that the user may or may not see:
items: [
{ title: 'Guide', icon: '$guide', component: 'Guide', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Courses', icon: '$courses', component: 'Course', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Sections', icon: '$sections', component: 'Sections', claims: '', size: '', roles: ['superAdmin', 'admin'] },
{ title: 'Units', icon: '$units', component: 'Units', claims: '', size: '', roles: ['superAdmin', 'admin'] },
{ title: 'Groups', icon: '$groups', component: 'Groups', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Users', icon: '$users', component: 'Users', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'FAQ', icon: '$faq', component: 'FAG', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
]
and an admin object. This is the user and their permission roles:
cid: (...)
email: (...)
emailVerified: (...)
fullPath: (...)
id: undefined
roles: Array(2)
0: "member"
1: "pastor"
Here is my code:
const hasRole = this.items.filter(val => this.admin.roles.includes(val.roles))
return hasRole
This code no longer works because the items.roles used to only be a string but I have now made it an array of roles.
I have tried multiple combinations but am struggling to figure this out.
Use Array.some() to test if any element in an array satisfies a condition. In this case, the condition would be if the element is found in another array.
const hasRole = this.items.filter(val =>
this.admin.roles.some(role => val.roles.includes(role))
)
return hasRole
Change to Array.every() instead if all roles in the this.admin object should be included to result in a positive result.
I see there is already a solution, anyway I post also mine. If you want to filter the array and get only items with specified role then you can try this:
let items= [
{ title: 'Guide', icon: '$guide', component: 'Guide', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Courses', icon: '$courses', component: 'Course', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Sections', icon: '$sections', component: 'Sections', claims: '', size: '', roles: ['superAdmin', 'admin'] },
{ title: 'Units', icon: '$units', component: 'Units', claims: '', size: '', roles: ['superAdmin', 'admin'] },
{ title: 'Groups', icon: '$groups', component: 'Groups', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Users', icon: '$users', component: 'Users', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'FAQ', icon: '$faq', component: 'FAG', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
]
let admin = {
roles: {
0: "member",
1: "pastor"
}
}
let filtered = {}
for(role in admin.roles){
itemsWithSpecificRole = items.filter(val => val.roles.includes(admin.roles[role]))
Object.assign(filtered, itemsWithSpecificRole)
}
console.log(filtered)
When i use refresh button in my browser or hit f5 on keyboard instead of refreshing my page it redirects to home page.
Code
router.js
import Vue from "vue";
import VueRouter from 'vue-router';
import store from './store';
Vue.use(VueRouter);
import NotFoundComponent from './components/NotFoundComponent.vue';
const router = new VueRouter({
mode: "history",
routes: [
{
path: '*',
name: 'notFound',
component: NotFoundComponent,
meta: {
breadCrumb: 'Not Found'
}
},
//rest of routes...
]
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters.isLoggedIn) {
next({
name: 'login'
})
} else {
next()
}
}
if (to.matched.some(record => record.meta.admin)) {
if (store.getters.loggedUser.type !== 'admin') {
next({
name: 'home'
})
} else {
next()
}
}
next()
});
router.afterEach((to, from) => {
Vue.nextTick(() => {
document.title = to.pageTitle || 'Test App';
});
});
export default router;
For instance if i am in this URL
https://example.com/products
after refresh i will redirect to
https://example.com
Any idea?
Update
route.js full code
import Vue from "vue";
import VueRouter from 'vue-router';
import store from './store';
Vue.use(VueRouter);
//admins
import pageHome from './components/HomePage.vue';
import Dashboard from './components/admin/Dashboard.vue';
import AdminProducts from './components/admin/Products/Products.vue';
import AddProducts from './components/admin/Products/Add.vue';
import CurrencySettings from './components/admin/Settings/Currencies/Currency.vue';
import AddCurrencies from './components/admin/Settings/Currencies/Add.vue';
import editCurrencies from './components/admin/Settings/Currencies/Edit.vue';
import SlideSettings from './components/admin/Settings/Slides/Slide.vue';
import addSlides from './components/admin/Settings/Slides/Add.vue';
import editSlides from './components/admin/Settings/Slides/Edit.vue';
import categoriesSettings from './components/admin/Categories/Categories.vue';
import addCategories from './components/admin/Categories/Add.vue';
import editCategories from './components/admin/Categories/Edit.vue';
import tagsSettings from './components/admin/Tags/Tags.vue';
import addTags from './components/admin/Tags/Add.vue';
import editTags from './components/admin/Tags/Edit.vue';
import brandsSettings from './components/admin/Brands/Brands.vue';
import addBrands from './components/admin/Brands/Add.vue';
import editBrands from './components/admin/Brands/Edit.vue';
import usersSettings from './components/admin/Users/Users.vue';
import addUsers from './components/admin/Users/Add.vue';
import editUsers from './components/admin/Users/Edit.vue';
import reviewsSettings from './components/admin/Reviews/Reviews.vue';
import editReviews from './components/admin/Reviews/Edit.vue';
// users
import Register from './components/auth/Register.vue';
import Login from './components/auth/Login.vue';
import Profile from './components/auth/Profile.vue';
import SingleProduct from './components/Front/SingleProduct.vue';
import NotFoundComponent from './components/NotFoundComponent.vue';
const router = new VueRouter({
mode: "history",
routes: [
{
path: '*',
name: 'notFound',
component: NotFoundComponent,
meta: {
breadCrumb: 'Not Found'
}
},
// ADMIN ROUTES
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
name: 'dashboard',
breadCrumb: 'Dashboard'
}
},
{
path: '/dashboard/products',
name: 'adminProducts',
component: AdminProducts,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Products'
}
},
{
path: '/dashboard/products/add',
name: 'addProducts',
component: AddProducts,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Add Product'
}
},
{
path: '/dashboard/currencies',
name: 'CurrencySettings',
component: CurrencySettings,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Currencies'
}
},
{
path: '/dashboard/currencies/add',
name: 'addCurrencies',
component: AddCurrencies,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Add Currency'
}
},
{
path: '/dashboard/currencies/:id/edit',
name: 'editCurrencies',
component: editCurrencies,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Edit Currency'
}
},
{
path: '/dashboard/slides',
name: 'SlideSettings',
component: SlideSettings,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Slides'
}
},
{
path: '/dashboard/slides/add',
name: 'addSlides',
component: addSlides,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Add Slide'
}
},
{
path: '/dashboard/slides/:id/edit',
name: 'editSlides',
component: editSlides,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Edit Slider'
}
},
{
path: '/dashboard/categories',
name: 'categoriesSettings',
component: categoriesSettings,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Categories'
}
},
{
path: '/dashboard/categories/add',
name: 'addCategories',
component: addCategories,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Add Category'
}
},
{
path: '/dashboard/categories/:id/edit',
name: 'editCategories',
component: editCategories,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Edit Category'
}
},
{
path: '/dashboard/tags',
name: 'tagsSettings',
component: tagsSettings,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Tags'
}
},
{
path: '/dashboard/tags/add',
name: 'addTags',
component: addTags,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Add Tag'
}
},
{
path: '/dashboard/tags/:id/edit',
name: 'editTags',
component: editTags,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Edit Tag'
}
},
{
path: '/dashboard/brands',
name: 'brandsSettings',
component: brandsSettings,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Brands'
}
},
{
path: '/dashboard/brands/add',
name: 'addBrands',
component: addBrands,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Add Brand'
}
},
{
path: '/dashboard/brands/:id/edit',
name: 'editBrands',
component: editBrands,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Edit Brand'
}
},
{
path: '/dashboard/users',
name: 'usersSettings',
component: usersSettings,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Users'
}
},
{
path: '/dashboard/users/add',
name: 'addUsers',
component: addUsers,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Add User'
}
},
{
path: '/dashboard/users/:id/edit',
name: 'editUsers',
component: editUsers,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Edit User'
}
},
{
path: '/dashboard/reviews',
name: 'reviewsSettings',
component: reviewsSettings,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Reviews'
}
},
{
path: '/dashboard/reviews/:id/edit',
name: 'editReviews',
component: editReviews,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Edit Review'
}
},
// public routes
{
path: "/",
name: 'home',
component: pageHome,
meta: {
breadCrumb: 'Home Page'
}
},
{
path: "/products/:slug",
name: 'SingleProduct',
component: SingleProduct,
meta: {
breadCrumb: 'Product'
}
},
// auth
{
path: '/profile',
name: 'profile',
component: Profile,
meta: {
requiresAuth: true,
breadCrumb: 'Profile'
}
},
{
path: '/register',
name: 'register',
component: Register,
meta: {
breadCrumb: 'Register'
}
},
{
path: '/login',
name: 'login',
component: Login,
meta: {
breadCrumb: 'Login'
}
}
]
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters.isLoggedIn) {
next({
name: 'login'
})
} else {
next()
}
}
if (to.matched.some(record => record.meta.admin)) {
if (store.getters.loggedUser.type !== 'admin') {
next({
name: 'home'
})
} else {
next()
}
}
next()
});
router.afterEach((to, from) => {
Vue.nextTick(() => {
document.title = to.pageTitle || 'Test App';
});
});
export default router;
Solved
working code
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!store.getters.isLoggedIn) {
next({
name: 'login'
})
} else {
next()
}
}
if (to.matched.some(record => record.meta.requiresAdmin)) {
// this route requires auth, check if logged in
// if not, redirect to home page.
if (!store.getters.loggedUser.type == 'admin') {
next({
name: 'home'
})
} else {
next()
}
}
else {
next() // make sure to always call next()!
}
})
Hope it help others.
I have the following:
children: [
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/basic')
},
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/Basic')
},
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/Basic')
}
]
I want to follow this structure, but programmatically create each dictionary using each record returned from an API call.
example api call
function getData() {
axios.get(Url + input.value)
.then(function (response) {
json_data = response.data;
});
}
so in python this would probably look something like:
test_list=[]
for item in json_data:
dict = {
name: item.name
path: item.path
meta: {
label: item.label,
link: item.link,
},
component: lazyLoading('testitem/basic')
},
test_list.append(dict)
children: test_list
How can I accomplish this in javascript? I'm having a real hard time learning javascript after doing python.
UPDATE:
This is the full code block that I am working with.
export default {
name: 'test',
meta: {
icon: 'fa-android',
expanded: false
},
children: [
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/Basic')
}
]
}
You were very close:
const children = [];
json_data.forEach(item => {
const dict = {
name: item.name,
path: item.path,
meta: {
label: item.label,
link: item.link,
},
component: lazyLoading('testitem/basic'),
}
children.push(dict);
});