how to set default route in vuejs with multiple pages - vue.js

I'm using vue cli and implemented a multiple page application in vue.config.js:
module.exports = {
pages: {
bla: {
entry: 'src/pages/bla/main.js',
template: 'public/index.html',
title: 'blaaaaa',
},
foo: {
entry: 'src/pages/foo/main.js',
template: 'public/index.html',
title: 'foooooo',
}
}
}
In /router/index.js:
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{ path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFoundView.vue },
{ path: '/', redirect: '/bla' },
{ path: '/bla', name: 'Bla', component: () => import('#/views/bla/BlaView.vue') },
{ path: '/foo', name: 'FooView', component: () => import('#/views/foo/MoiView.vue') },
{ path: '/foo/bar', name: 'FooBarView', component: () => import('#/views/foo/FooBarView.vue') },
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
All this works fine, but I don't see how to add a default route for root, although the documentation on Redirect and Alias seems clear. Going to '/' should redirect to '/bla' but vue isn't even detected on the page. Same problem with the NotFound page I tried: vue is not found.

Related

Localized Url : Vue3 + vite + vite-plugin-vue-i18n

I'm trying to get some localized url for my current project. So far I made a Lang dropdown that save the language in local storage for the next access to the website, Translations are imported from .json (with the help of vite-plugin-vue-i18n) files and work. So the translation is working The route that is commented work but when I introduce a Lang variable. I get: TypeError: guard.call is not a function. Any idea ?
Router.js
import {createRouter, createWebHistory} from "vue-router";
import Home from '../pages/Home.vue'
import About from '../pages/About.vue'
import i18n from '../locales/i18n'
/*const routes = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/about',
name: 'About',
component: About,
}
]*/
let locale = 'en'
if(localStorage.getItem('lang')) {
locale = localStorage.getItem('lang')
}
i18n.locale = locale;
const routes = [
{
path: '/',
redirect: `/${i18n.locale}`
},
{
path: `/${i18n.locale}`,
component: {
beforeRouteEnter: `/${i18n.locale}`,
beforeRouteUpdate: `/${i18n.locale}`,
render(h) { return h('router-view'); }
},
children: [
{
path: '/',
name: 'home',
component: Home,
},
{
path: 'about',
name: 'about',
component: About,
}
]
}
]
const router = createRouter({
history: createWebHistory(),
routes,
})
export default router;

URL of a deep nested route changes but not its view

Update: I can see the url changing in the address bar but the page contents doesnt change.
I have just started learning vue js recently and I am currently facing an issue with deep nested routes. Whenever I try to access the deep nested route I encounter a 404. The route that gives me 404 is on "/classes/new".
Router.js
import { createRouter, createWebHistory } from "vue-router";
import AdminLayout from "./layouts/AdminLayout";
import NotFound from "./pages/NotFound";
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: "/",
redirect: "dashboard",
component: AdminLayout ,
children: [
{
path: "/dashboard",
name: "dashboard",
component: () => import("./pages/Dashboard")
},
{
path: "/courses",
name: "courses",
component: () => import("./pages/Courses")
},
{
path: "/classes",
name: "classes",
component: () => import("./pages/Classes/Classes"),
children: [
{
path: "/new",
name: "new",
component: () => import("./pages/Classes/AddClass"),
}
]
},
{
path: "/categories",
name: "categories",
component: () => import("./pages/Categories")
}
]
},
{ path: "/:NotFound(.*)", component: NotFound }
]
});
export default router;
I think your children path should not start with a slash.
try path: "new" instead of path: "/new" ?

"npm run dev" creates 0.js, 1.js, ... 14.js files in my public folder

I'm a beginner using Webpack, NPM and VueJS.
I dont know what I did and I can't find any solution on internet.
When I run the command npm run dev in VueJS, webpack creates 15 files numbered from 0.js to 14.js
The files first lines are :
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],{
Where 0 in the file name
Anyone knows what I broke in my app ?
EDIT:
I figured out that every file is related to One component.
And I guess that this is in relation with my router file :
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
function loadView(view) {
return () => import(`../components/${view}.vue`);
}
function loadLayout(view) {
return () => import(`../components/_layouts/${view}.vue`);
}
const routes = [
// USER ROUTES
{
path: '/dashboard',
component: loadView('user/Dashboard'),
meta: {
layout: loadLayout('user/Layout'),
auth: "user"
},
name: 'user'
},
// SUPPLIER ROUTES
{
path: '/supplier',
component: loadView('supplier/Dashboard'),
meta: {
layout: loadLayout('supplier/Layout'),
auth: "supplier"
},
name: 'supplier'
},
// ADMIN ROUTES
{
path: '/admin',
component: loadView('admin/Dashboard'),
meta: {
layout: loadLayout('admin/Layout'),
auth: "admin"
},
name: 'admin'
},
// DEFAULT ROUTES
{
path: '/register',
component: loadView('auth/Register'),
meta: {
layout: loadLayout('home/Layout'),
auth: false
},
name: 'register'
},
{
path: '/login',
name: 'login',
component: loadView('auth/Login'),
meta: {
layout: loadLayout('home/Layout'),
auth: false
}
},
{
path: '/',
component: loadView('home/Home'),
meta: {
layout: loadLayout('home/Layout'),
auth: undefined
},
name: 'home'
},
// otherwise redirect to home
{
path: '*',
redirect: '/'
}
];
Vue.router = new Router({
hashbang: false,
mode: 'history',
routes
});
export default Vue.router;
To move those dynamic imports, you have to put this code in webpack.mix.js :
mix.webpackConfig({
output: {
chunkFilename: 'js/[name].js',
},
});

How to create child routes in vue js using Vue-Router and Laravel?

My application was working fine, until I changed my router.js file slightly to have child routes, and now my app is breaking, I can't see anything on any routes.
I get this error:
app.js:191 Uncaught TypeError: Cannot read property 'bind' of undefined
I can see that it points to this line:
var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);
in this file /public/js/app.js inside this block of code:
// on error function for async loading
__webpack_require__.oe = function(err) { console.error(err); throw err; };
var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || [];
var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);
jsonpArray.push = webpackJsonpCallback;
jsonpArray = jsonpArray.slice();
for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);
/******/ var parentJsonpFunction = oldJsonpFunction;
Has anyone come across something like this? I tried searching on google and there wasn't that much about it, I found something that said they updated their cli#3.0.0-rc.5 to rc.6 and it solved it for that 1 person, but that didn't solve it for me.
Working router.js:
import Vue from 'vue';
import VueRouter from 'vue-router';
import Dashboard from './views/Dashboard';
import Login from './views/Login';
import Register from './views/Register';
import Forms from './views/Forms';
import CandidateProfileCreate from './views/candidate/CandidateProfileCreate';
import CandidateProfileIndex from './views/candidate/CandidateProfileIndex';
Vue.use(VueRouter);
const routes = [
{
path: '/',
name: 'dashboard',
component: Dashboard
},
{
path: '/candidate-profile/create',
name: 'candidate-profile-create',
component: CandidateProfileCreate
},
{
path: '/candidate-profile',
name: 'candidate-profile',
component: CandidateProfileIndex
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '/register',
name: 'register',
component: Register
},
{
path: '/forms',
name: 'forms',
component: Forms
}
]
const router = new VueRouter({
mode: 'history',
routes: routes,
linkActiveClass: 'active'
});
export default router;
Getting error, router.js:
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from './views/Home';
Vue.use(VueRouter);
const routes = [
{
path: '/home',
component: Home,
children: [
{
path: '',
name: 'dashboard',
component: () => import('./views/Dashboard.vue')
},
{
path: 'candidate-profile',
name: 'candidate-profile-index',
component: () => import('./views/candidate/CandidateProfileIndex')
},
{
path: '/candidate-profile/create',
name: 'candidate-profile-create',
component: () => import('./views/candidate/CandidateProfileCreate')
},
],
},
{
path: '/login',
name: 'login',
component: () => import('./views/Login.vue')
},
{
path: '/register',
name: 'register',
component: () => import('./views/Register.vue')
},
{
path: '/forms',
name: 'forms',
component: () => import('./views/Forms.vue')
}
]
const router = new VueRouter({
mode: 'history',
routes: routes,
linkActiveClass: 'active'
});
export default router;
You must create children in object you want.
Like this
if you put path of father element to his children
this page will be open when page create
{
path: '/home',
component: Home,
children: [
{
path: '/home',
name: 'dashboard',
component: () => import('./views/Dashboard.vue')
},
{
path: 'candidate-profile',
name: 'candidate-profile-index',
component: () => import('./views/candidate/CandidateProfileIndex')
},
{
path: '/candidate-profile/create',
name: 'candidate-profile-create',
component: () => import('./views/candidate/CandidateProfileCreate')
},
],
},

Middleware for routes in vue

I want to deny some routes for authorized users, like login page, register page, but I don't know how to make those middlewares
Routes
routes: [
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/register',
name: 'Register',
component: Register
}
]
Function that I use in components
computed: {
isLoggedIn () {
return this.$store.getters.isLoggedIn
}
}
In your router you can do something like this.
All routes marked with meta: { requiresLogin: true} } will be checked in the BeforeEach method. Here we redirect them to the login page.
You can in principle halt the router and show a modal or whatever you like here.
Router
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from '../views/App.vue'
import Login from '../views/login.vue'
import Register from '../views/registser.vue'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
{ path: '/', name: 'app', component: App, meta: { requiresLogin: true} },
{ path: '/login', name: 'login', component: Login },
{ path: '/register', name: 'register', component: Register },
]
})
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresLogin)) {
if (**USER IS NOT LOGGED IN**) {
next({
path: '/login',
query: {
redirect: to.fullPath,
},
});
} else {
next();
}
} else {
next();
}
})
export default router
Create additional meta field requiresAuth in your routes to specify which route require logged user:
routes: [{
path: '/',
name: 'Dashboard',
component: Dashboard,
children: [{
path: 'settings',
name: 'Settings',
component: Settings,
meta: {
requiresAuth: true
}
}],
meta: {
requiresAuth: true
}
},
{
path: '/login',
name: 'Login',
component: Login
}
],
Then add middleware in main.js:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
const authUser = JSON.parse(window.localStorage.getItem('authUser')) // your oauth key
if (authUser && authUser.access_token) {
next()
} else {
next({
name: 'Login'
})
}
}
next()
})
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: {
App
}
})