VueJS how to register global before guards - vuejs2

beforeEach hook for every route like in the docs:
My page should scroll to the top on route change.
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
window.scrollTo(0, 0)
next();
})
but my router has another structure and its not working:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '#/components/HelloWorld'
import Contact from '#/components/Contact'
Vue.use(Router)
export default new Router({
beforeEach: (to, from, next) => {
window.scrollTo(0, 0)
next();
},
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/kontakt',
name: 'Contact',
component: Contact
},
]
})
Thanks in advance =)
Or is it better to use the .created hook on the components to scroll to the top of the page?
created() {
window.scrollTo(0, 0);
}

You can adapt your code to the structure required in the docs:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '#/components/HelloWorld'
import Contact from '#/components/Contact'
Vue.use(Router)
// create object router with the valid initialization
const router = new Router({
routes: [{
path: '/',
name: 'HelloWorld',
component: HelloWorld
}, {
path: '/kontakt',
name: 'Contact',
component: Contact
}, ]
});
// add the beforeEach hook
router.beforeEach((to, from, next) => {
window.scrollTo(0, 0);
next();
});
// export router as default
export default router;

I think you should put Router.beforeEach after creating router.

Related

How to add router with query param to router list?

I want to add a route with query params.
If the url is blog, then navigate to index page.
If the url includes the author query param, replace a component on the page with the BlogAuthorPage component.
router: {
extendsRoutes(routes, resolve) {
routes.push({
name: 'author-page-detail',
path: '/blog?author=*',
component: resolve(__dirname, 'pages/blog/author-page.vue')
})
}
}
This should not be done in nuxt.config.js's router key but rather in your blog.vue page directly with a component router guard.
The code below should be enough to check if the route does have a author query params and redirect to the blog/author-page page.
<script>
export default {
beforeRouteEnter(to, from, next) {
next((vm) => {
if (vm.$route.query?.author) next({ name: 'blog-author-page' })
else next()
})
},
}
</script>
I use "#nuxtjs/router": "^1.6.1",
nuxt.config.js
/*
** #nuxtjs/router module config
*/
routerModule: {
keepDefaultRouter: true,
parsePages: true
}
router.js
import Vue from 'vue'
import Router from 'vue-router'
import BlogIndexPage from '~/pages/blog/index'
import BlogAuthorPage from '~/pages/blog/author-page';
Vue.use(Router);
export function createRouter(ssrContext, createDefaultRouter, routerOptions, config) {
const options = routerOptions ? routerOptions : createDefaultRouter(ssrContext, config).options
return new Router({
...options,
routes: [
...options.routes,
{
path: '/blog',
component: ssrContext.req.url.includes('/blog?author') ? BlogAuthorPage : BlogIndexPage
}
]
})
}

Vue - Can I change a routers component based on the value of an item in the store?

So I want to change a routers component based on a state in my store. This means that, depending on the state in the store, the router can display a different template page.
Router.js:
import Router from 'vue-router'
import store from './store'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Homepage',
component: () => import('#/' + store.state.theme.path + '/components/Hello')
},
{
path: '/admin',
name: 'Admin',
component: () => import('#/cms/components/Admin')
}
]
})
Store.js:
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
theme: {
path:'theme-00'
}
},
getters: {
theme: state => {
return state.theme.path;
}
}
});
Any help is welcome!
Thanks,
Justin.

Vue Js Axios get method

I use vue.js and I try to set a parameter id in axios.get request and I can't understand how exactly to do it
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Movie from './views/Movie.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
},
{
path: '/movie/:m_id',
name: 'movie',
component: Movie
}
]
})
import Navbar from '../components/Navbar'
import axios from "axios"
export default {
components:{
Navbar
},
data () {
return {
movi: null,
}
},
mounted () {
axios
.get(`https://api.themoviedb.org/3/movie/${m_id}?api_key=7bc75e1ed95b84e912176b719cdeeff9&language=en-US`)
.then(response => (this.movi= response.data))
}
}
I am trying to pass to axios this id of the page to get information about that specific movie and I got stuck.
Any help?
You can try this to use your params from the URL:
// Retrieve the `m_id` param from the `this.$route.params` object:
this.$route.params.m_id
For more info see https://router.vuejs.org/api/#route-object-properties
#How can I do the same thing but in Vuex
import Vue from 'vue'
import Vuex from 'vuex'
import Axios from 'axios';
import router from './router'
Vue.use(Vuex)
Vue.use(Axios)
Vue.use(router)
export default new Vuex.Store({
// data() {
// return {
// m_id:this.$route.params.m_id
// }
// },
// m_id : this.$route.params.m_id,
state: {
video_key: [],
},
mutations: {
updateInfo (state , video_key){
state.video_key = video_key
}
},
getters:{
m_id : this.route.params.m_id
},
actions: {
fetchData({commit,getters}){
axios.get(`https://api.themoviedb.org/3/movie/${this.m_id}/videos?api_key=7bc75e1ed95b84e912176b719cdeeff9&language=en-US`)
.then(response =>{
commit('updateInfo',response.data.results[0].key)
})
}
}
})

Vue: beforeEach is not a function

Route change doesn't scroll to top, so Vue creator advises to use navigation guards. In the updated version:
Router.beforeEach(function (to, from, next) {
window.scrollTo(0, 0)
next();
})
Perfect, except it yields this fatal error in my app: ncaught TypeError: vue_router__WEBPACK_IMPORTED_MODULE_1__.default.beforeEach is not a function
Why?
Just in case here's my complete router.js file:
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import PastEvents from './views/PastEvents.vue'
import BasicPage from './views/BasicPage.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/past-events',
name: 'past-events',
component: PastEvents
},
{
path: '/basic-page',
name: 'basic-page',
component: BasicPage
}
]
})
Router.beforeEach(function (to, from, next) {
window.scrollTo(0, 0)
next();
})
You've capitalized Router, that's the class name. What you want to do is add your .beforeEach() to the instance of the router. You'll notice in the documentation that it's always a lowercase router they're adding the guards to.
Currently, you're immediately exporting the instance from the module, so you'll need to first add it to a variable when you create a new Router and then add your .beforeEach() clauses to it before finally exporting it.
const router = new Router({
...
})
router.beforeEach( ... )
export default router

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();
}
});