[Solved] Using router from vuex action
-
I’m trying to reroute the user after an action.
I configured the routes:
const routes = [ { path: '/', component: () => import('layouts/layout.vue'), children: [ { path: '', component: () => import('pages/Index.vue') }, { path: 'myPage', component: () => import('pages/myPage.vue') } ] } ] if (process.env.MODE !== 'ssr') { routes.push({ path: '*', component: () => import('pages/Error404.vue') }) } export default routes
And I kept the default configuration for the router.
import Vue from 'vue' import VueRouter from 'vue-router' import routes from './routes' Vue.use(VueRouter) /* * If not building with SSR mode, you can * directly export the Router instantiation */ export default function (/* { store, ssrContext } */) { const Router = new VueRouter({ scrollBehavior: () => ({ y: 0 }), routes, // Leave these as is and change from quasar.conf.js instead! // quasar.conf.js -> build -> vueRouterMode mode: process.env.VUE_ROUTER_MODE, base: process.env.VUE_ROUTER_BASE }) return Router }
I can access myPage with a click on
<router-link>
<template> <q-page> <router-link to="/myPage">my page</router-link> </q-page> </template> <script> export default { name: 'PageIndex', }
But I want to access it from a vuex action…
import router from '../../../router' export const myAction = context => { // code router().push({path: '/myPage'}) }
…that I can dispatch in my previous component
<template> <q-page> <router-link to="/myPage">my page</router-link> <q-btn @click="myAction">my page</q-btn> </q-page> </template> <script> import { mapActions } from 'vuex' export default { name: 'PageIndex', methods: { ...mapActions([ 'myAction' ]) } } </script>
And, while the
<router-link>
works well, when I click the<q-btn>
, the address bar shows the correct path (http://localhost:8080/#/myPage
), but theMyPage
page isn’t loaded. It only loads when I refresh the page.What am I doing wrong ?
-
export function myAction () { // code this.$router.push({path: '/myPage'}) }
-
@rstoenescu It doesn’t work since actions are not a vue component. I need to import the router to interact.
If I use your syntax, I get an error messageTypeError: "_this is undefined"
-
The error suggests you’re still using arrow function instead of normal function as I indicated.
-
@rstoenescu It works. Thanks a lot !