VUEJS remove added routes or clear added routes - vue.js

Good Day Everyone,
I'm trying to remove the addedRoutes on vuejs.. after doing hours of research on vue-router documentation I can't find a method that can clear the addedRoutes.
Here's my code:
new Vue({
el: '#app',
render: h => h(App),
router:router,
data(){
return{
isAuth:null
}
},
created(){
this.checkAuthentication();
if(this.isAuth){
this.getUserRole();
}
bus.$on('reload', (passData) => {
this.getUserRole();
if(this.isAuth){
this.getUserRole();
}
});
},
methods:{
getUserRole(){
this.$http.get('api/users/getRole').then(response => {
console.log(response);
if(response.body.is_admin){
router.addRoutes(Routes);
}else if(response.body.is_buh){
router.addRoutes(BUHRoutes);
}else if(response.body.is_so) {
}
});
},
checkAuthentication(){
this.isAuth = this.$auth.isAuthenticated();
}
}
});
my scenario is that when I login and if it is successful I get the userRole and based on that user role I add the routes router.addRoutes() based on the userRole. however, when I logout I get this warning on my console log [vue-router] Duplicate named routes definition: { name: "division-maintenance", path: "/division-maintenance" }. that's why I was doing a research on how to clear the addedRoutes.
any help will be appreciated.

I create a example file with vue-route
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
Vue.use(Router)
export default new Router({
base: process.env.BASE_URL, //config url base
routes: [
{
path: '/home',
name: 'home',
component: Home
},
],
mode: 'history'
})
The property mode: 'history' removes #

Related

Vue.js routes send to 404 on refresh

I have made routes, if click on link in website it works as it should. But when you on that page (for example /aboutUs) and refresh it or simply copy url, paste it and hit Enter it shows Page not found. How to fix it? Run out of ideas, can't find answer that works anywhere
main.js below:
Vue.config.productionTip = false;
Vue.use(VueRouter);
Vue.prototype.$careerEmpty = false;
const router = new VueRouter({
mode:'history',
scrollBehavior(to, from, savedPosition){
if (to.hash) {
return { selector: to.hash}
} else if (savedPosition) {
return savedPosition;
} else {
return {x:0, y:0}
}
},
routes
});
new Vue({
router,
render: h => h(App),
}).$mount('#app')
routes.js below:
import firstPage from "#/components/Pages/firstPage";
import aboutUsPage from "#/components/Pages/aboutUsPage";
import pageNotFound from "#/components/pageNotFound";
const routes = [
{path: '/', component: firstPage},
{path: '/aboutUs', component: aboutUsPage},
{path: '/404', component: pageNotFound},
{path: '*', redirect: '/404'},
];
export default routes;
You can use vue router history mode.
Check here
Vue.use(Router, {
mode: 'history'
});

correct setting prerender-spa-plugin

I am trying to configure a prerender-spa-plugin for my application.
Need to configure for multiple pages.
I do, as in documentation (Vue.js 2 Router)
I added the necessary parameters to file webpack.prod.config.js
const PrerenderSPAPlugin = require('prerender-spa-plugin')
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer
const webpackConfig = merge(baseWebpackConfig, {
...
plugins: [
// == PRERENDER SPA PLUGIN == //
new PrerenderSPAPlugin({
staticDir: path.join(__dirname, '../dist'),
routes: ['/', '/test'],
renderer: new Renderer({
inject: {
foo: 'bar'
},
headless: false,
renderAfterDocumentEvent: 'render-event'
})
}),
...
Also in the file main.js
new Vue({
el: '#app',
router,
render: h => h(App),
mounted () {
// You'll need this for renderAfterDocumentEvent.
document.dispatchEvent(new Event('render-event'))
}
})
Now about the main problem.
At the root(/) of the project, pre-rendering is working.
If you go to the page /test, then in the source code (ctrl + u) will show the code from the site root(/).
I can't find content from /test in any way.
Tell me what I'm doing wrong, and how to fix the problem.
Thank!
UPD:routes.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '#/components/HelloWorld'
import test from '#/components/test'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/test',
name: 'test',
component: test
}
]
})

VueJS : Routing confusion

probably a stupid question especially as I am not sure if I am using VueJS or VueJS 2.0 but I am trying to get simple routing working where I can pick up the parameters / the path of the URL.
For example http://127.0.0.1/search/*****
Here is my main.js
import Vue from 'vue'
import App from './components/App'
import VueRouter from 'vue-router'
const routes = [
{ path: '/', name: 'Home', component: App },
{ path: 'search/:id', name: 'Search', component: App }
];
const router = new VueRouter({ mode: 'history', routes: routes });
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
render: h => h(App)
})
And on my App.component I am trying to get the :id
created: function() {
//this.filterTutorials();
this.searchTerm = this.$route.query.id;
if (this.searchTerm == null) {
this.searchTerm = this.$route.params.id;
}
console.log(this.searchTerm)
}
UPDATE
App and search were the same component but I have not split them out (same directory)
New main.js. It is not even calling the search page
import Vue from 'vue'
import App from './components/App'
import VueRouter from 'vue-router'
const routes = [
{ path: '/', name: 'Home', component: App },
{ path: '/search/:id', name: 'Search', component: () => import(/* webpackChunkName: "search" */ './components/Search.vue'), props: true }
];
const router = new VueRouter({ mode: 'history', routes: routes });
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
render: h => h(App)
})
I have also updated webpacks
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
vue: 'vue/dist/vue.js'
}
},
In your case, App is statically created before the route even resolves, so the created lifecycle hook would check for route parameter before it even existed (i.e., it would be undefined). I noticed both /search and / point to App, but you probably meant a component name like Search.
You can either dynamically import Search:
const routes = [
{
path: '/search/:id',
name: 'Search',
component: () => import(/* webpackChunkName: "search" */ './views/Search.vue')
}
]
Or you could use VueRouter's props: true to automatically set Search's id prop on navigation, obviating the check for the route parameters from created().
const routes = [
{
path: '/search/:id',
name: 'Search',
component: () => import(/* webpackChunkName: "search" */ './views/Search.vue'),
props: true,
}
]
demo

VueRouter's beforeEach causes error: failed to convert exception to string

My console says:
[vue-router] uncaught error during route navigation:
<failed to convert exception to string>
The line that causes that error is the one in main.js:
next('/login')
my main.js file:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Vuex from 'vuex'
import App from './App.vue'
import Routes from './routes'
import { store } from './store/store';
Vue.use(VueRouter);
const router = new VueRouter({
routes: Routes
})
router.beforeEach((to, from, next) => {
next('/login');
})
var vm = new Vue({
el: '#app',
store: store,
router: router,
render: h => h(App),
})
My routes.js file:
export default [
{ path: '/', component: Game, cors: true },
{ path: '/login', component: Login },
{ path: '/signin', component: SignIn },
{ path: '/gamerouter', component: GameRouter },
{ path: '/waitingforplayers', component: WaitingForPlayers, name: "buba" },
{ path: '/selectPlayersForTeams', component: SelectPlayersForTeams },
{ path: '/startStatistics', component: StartStatistics },
{ path: '/gamelocked', component: GameLocked },
{ path: '/answering', component: Answering },
]
I also get this error if i put next('/'), but i do not get this error if i write next() or next(false);
Any ideas that might help me fix this?
next has to be called without parameters to confirm navigation, otherwise you will keep triggering the beforeEach hook:
router.beforeEach(function(to, from, next) {
console.log(to.path)
if (to.path !== '/timer') {
next("/timer");
} else {
next();
}
});

Vue.js App Element update data

I am trying to have a template in App.vue which is main component of my app and it contains navigation bar. However I would like to hide this bar when in login page, but I cannot force App.vue to update. Any help please? :)
App.vue - here I would like to have a flag if I should show toolbar and I want to use it in template. The main problem is that currentRoute.path doesn't get updated automatically. I also tried adding router.afterEach, but didn't manage to make it work.
<script>
export default {
name: 'app',
data() {
return {
msg: 'initial',
showToolbar: router.currentRoute.path !== '/login'
}
},
}
</script>
main.js
firebase.auth().onAuthStateChanged(function (user) {
if (!app) {
/* eslint-disable no-new */
app = new Vue({
el: '#app',
router,
components: {App},
template: '<App/>',
})
}
});
router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '#/components/Home'
import Login from '#/components/Login'
import VueMaterial from 'vue-material'
import 'vue-material/dist/vue-material.css'
Vue.use(VueMaterial);
Vue.use(VueRouter);
let router = new VueRouter({
routes: [
{
path: '*',
redirect: '/'
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/',
name: 'Home',
component: Home,
meta: {
requiresAuth: true
}
}
]
});
export default router;
You're currently setting up the initial value of showToolbar, but not setting it up to watch for route changes. For that to work, move showToolbar to the computed section of you App.vue vm:
export default {
name: 'app',
data() {
return {
msg: 'initial',
}
},
computed: {
showToolbar() { return this.$router.currentRoute.path !== '/login' }
}
}
Also, since you are not explicitly importing router in App.vue, you access it in App.vue vm like this.$router, not like router.