vue-router not pushing while inside a store - vue.js

This is my store
import Vue from 'vue'
import Vuex from 'vuex'
import router from '#/main';
import mainStore from './modules/main-store';
import loginStore from './modules/login-store';
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
mainStore,
loginStore
}
});
and my login-store.js
//other imports
import router from '#/main';
const actions = {
forceLogout(){
localStorage.removeItem('token')
localStorage.removeItem('user')
delete API.defaults.headers.common['Authorization']
router.push('/login')
},
//other actions
}
And my router.js:
import store from './stores'
Vue.use(Router)
const router = new Router({
mode: 'hash',
routes: [
{
path: '/login',
name: 'login',
component: Login,
},
]
//other routes
})
//... some router.afterEach and router.beforeEach
export default router
There is a case where I need the store to force a logout and this is how I do it, I call the forceLogout action from a file named api.js
import store from './../stores';
//....
if(error_msg == 'Not_Logged'){
store.dispatch('forceLogout')
}
//....
I've tried changing an import:
import router from 'vue-router'
//...
router.push('/login')
Same thing with importing
import router from '#/main'
router.push('/login')
and I keep on getting TypeError: Cannot read property 'push' of undefined

I don't see where you're exporting your router.
router.js should include export default router so then when you import router from '#/main' it actually imports something.

Related

cannot use vue-router routes in axios file

I need to redirect to login page if backend throws 401-Unauthorised error. But when I try to use router.push('/login) it throws router is not defined error in axios interceptor.
Here is my axios.js file.
import Vue from 'vue'
import axios from "axios"
import router from '../router'
_axios.interceptors.response.use(
function(response) {
return response
},
function(error) {
if(error.response.status == 401){
router.push('/login')
}
return Promise.reject(error)
}
)
This is router.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
Vue.use(VueRouter)
const routes = [
{
path: '/login',
name: 'Login',
meta: {
layout: 'login',
requireAuth: false,
icon: null
},
component: () => import(/* webpackChunkName: "login" */
'../components/common/auth/login-form'),
}]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
And defining {router} in axios gives this error in terminal npm run serve:
If I try with import router from '../router' in axios file I got this error:
use default export import router from '../router' instead of named import like you have in answer, `cause you have default export only in file where you define router

Uncaught SyntaxError: The requested module '/node_modules/.vite/vue.js?v=535663ae' does not provide an export named 'default'

I'm using a js framework known as griptape(used for blockchain). I'm getting this error when trying to use the vue router.
import Vue from "vue"; //Error **does not provide an export named 'default'**
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
Vue.use(VueRouter);
const 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"),
},
];
const router = new VueRouter({
routes,
});
export default router;
while my vue.d.ts file looks like this
import { CompilerOptions } from '#vue/compiler-dom';
import { RenderFunction } from '#vue/runtime-dom';
export declare function compile(template: string | HTMLElement, options?: CompilerOptions): RenderFunction;
export * from "#vue/runtime-dom";
export { }
router.d.ts file look like this
I think you are using Vue 3. You should check your vue-router version. If you just run npm i vue-router now, the version should be "^3.5.3". Try to use npm i vue-router#next to install newer version.
Then export router like this:
import {createRouter, createWebHistory} from 'vue-router'
const routes = [
{
path:'/',
name:"Home",
component:()=>import('./pages/Home.vue')
}
,
{
path:'/about',
name:"About",
component:()=>import('./pages/About.vue')
}
]
const router = createRouter({
history:createWebHistory(),
routes
})
export default router
You technically didn't ask a question I will try to explain the error. Your error states what you try to do, importing a default export from the module 'vue' which doesn't exist.
// some ts file
import Vue from "vue";
// the module
export default {}
If there should be a named export called 'Vue' you should write it as follows: import { Vue } from 'vue'
references:
https://www.typescriptlang.org/docs/handbook/modules.html#default-exports

Importing Vue Router inside a JavaScript file causes 'Module Parse Failed' Error

I am trying to access the router in the interceptor of axios, but when I import the file in a .js Axios file, an error Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders > <template> occurs.
Here is a sample of the router.js file:
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
const router = {
base: process.env.BASE_URL,
routes: [
{
path: "/settings",
name: "settings",
component: require('#/views/Settings.vue'),
}
]
};
export default new Router(router);
And the interceptor file contains:
import router from './router';
Why do you using require('#/views/Settings.vue')?
Instead try to use import function.
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
const router = {
base: process.env.BASE_URL,
routes: [
{
path: '/settings',
name: 'settings',
component: () => import('#/views/Settings.vue'),
},
],
};
export default new Router(router);
PS: Answer your comment.
In main.js file export the instance variable:
import Vue from 'vue';
import App from './App.vue';
import router from './router';
Vue.config.productionTip = false;
let vm = new Vue({
router,
render: h => h(App),
}).$mount('#app');
export default vm; // ATENTION HERE
In axios.js file import the main.js and access the $router:
import vm from './main.js';
...
// YOUR INTERCEPTOR
vm.$router.push({ name: 'settings' });
...

vuejs2: How to pass vuex store to vue-router components

In case when vue-router is not used, store can be passed to child components when declaring new Vue()
But I am using both vue-router and vuex. In this case how can I make store available to components. For e.g. my store.js is typical:
import Vue from 'vue'
import Vuex from 'vuex'
import jwt_decode from 'jwt-decode'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(Vuex);
Vue.use(VueAxios, axios);
export const store = new Vuex.Store({
state: {
jwt: localStorage.getItem('t'),
endpoints: {
obtainJWT: 'http://0.0.0.0:8000/auth/obtain_token',
refreshJWT: 'http://0.0.0.0:8000/auth/refresh_token'
}
},
mutations: {
updateToken(state, newToken){
localStorage.setItem('t', newToken);
state.jwt = newToken;
},
removeToken(state){
localStorage.removeItem('t');
state.jwt = null;
}
},
actions:{
obtainToken(username, password){
//commented code
},
refreshToken(){
//commented code
},
inspectToken(){
//commented code
}
}
});
My main.js file is as below:
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
import { store } from './store'
console.log(store)
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
And router/index.js file is as below:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '#/components/HelloWorld'
import Signup from '#/components/signup/Signup'
import store from '../store.js'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/login',
name: 'Login',
component: function (resolve) {
require(['#/components/login/Login.vue'], resolve)
}
},
{
path: '/signup',
name: 'Signup',
component: Signup
}
]
})
Now how can I pass store to my Signup component. Even though I am passing store in new Vue() it is not available in Signup component
I think the problem is that you importing store and you use the ../store.js,but when you import js file you dont have to use the .js so it has to be import store from '../store'
Also you dont have to pass the vuex store in components using vue-router.
So follow below the installation of vuex store and vue-router!
Vuex Store:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
propertiesName: 'PropValue'
},
getters: {},
mutations: {},
actions: {}
});
Vue-Router:
import Vue from 'vue'
import Router from 'vue-router'
import Page from '#/components/Page.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/Page',
name: 'Page',
component: Page,
},
//other routes
],
mode: 'history',
scrollBehavior(to, from, savedPosition) {
if(savedPosition){ //when use press back button will go at the position he was on the page
return savedPosition
}
if(to.hash){ //if has a hash positition to go
return { selector: to.hash } //go to the page in scrolled Position
}
return { x:0, y: 0 } //go to the page in scroll = 0 Position
}
})
main.js:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import { store } from '../store/store'
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
Note:Doing that,now you have access of router and store in all your components
To use the store in your components:
this.$store.state.propertiesName
To use the router in your components:
this.$router.push({name: 'Page'})

Access router instance from my service

I create a auth service (src/services/auth.js), with just functions and properties ..
export default {
login() { ... }
...
}
Inside login function, I need to redirect user
router.go(redirect)
How can I retrieve router instance?
Context
In my src/main.js file, i create a router ..
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import route from './routes'
const router = new VueRouter({
history: false,
linkActiveClass: 'active'
})
route(router)
const App = Vue.extend(require('./App.vue'))
In my src/routers.js is just map routes
export default function configRouter (router) {
router.map({ .. })
}
You should export the router instance and then import it into the auth.js service.
Here is my workaround with some improvements:
src/routes.js
export default {
'/': {
component: {...}
},
'/about': {
component: {...}
},
...
}
src/router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Routes from './routes'
Vue.use(VueRouter)
const router = new VueRouter({...})
router.map(Routes)
// export the router instance
export default router
src/main.js
import Router from './router'
import App from './app'
Router.start(App, '#app')
src/services/auth.js
import Router from '../router'
export default {
login () {
// redirect
Router.go('path')
}
}
Is your auth service a Vue component?
If so, you should be able to change routes with:
this.$router.go('/new/route');