Accessing vue-router from actions.ts - vue.js

How do we get access to the Vue router instance from within our actions.ts file? this.$router and this.$route aren't available in the following context:
boot.ts:
import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';
import store from './services/store'
import * as log from 'loglevel'
Vue.use(VueRouter);
log.setLevel("trace");
const router = new VueRouter({
routes,
linkActiveClass: "active"
});
new Vue({
el: '#app-root',
router: router,
store: store,
render: h => h(require('./layouts/app.vue.html'))
});
actions.ts:
import { http, httpClass } from './http';
import { DomainAppModel } from '../models/domainApps';
import Vue from 'vue';
var actions = {
LOGOUT: function ({ commit }, params) {
return new Promise((resolve, reject) => {
http.logout().then(result => {
commit('CLEAR_STATE');
// this.$router and this.$route not available
this.$router.push({
path:"login",
query: {
sessionTimedout: true,
redirect: this.$route.fullPath
}
});
});
});
}
}
export default actions

$router:
In order to access $router in the store actions you can do it like this:
move your router declaration to a separate file named router.ts
const router = new VueRouter({
routes,
linkActiveClass: "active"
});
export default router;
Import your router in actions.ts and use it instead of this.$router like this:
import router from './router';
// then use the router like this
router.push({path: 'login'})
$route.fullPath
Concerning $route.fullPath, you can pass it as a property of the payload when the action is dispatched
this.$store.dispatch('LOGOUT', {redirectPath: this.$route.fullPath})
then use it like this in the LOGOUT action
router.push({path:"login", query: {
sessionTimedout: true,
redirect: params.redirectPath
}});

Related

Vue: Can't access Pinia Store in beforeEnter vue-router

I am using Vue 3 including the Composition API and additionally Pinia as State Management.
In the options API there is a method beforeRouteEnter, which is built into the component itself. Unfortunately this method does not exist in the composition API. Here the code, which would have been in the beforeRouteEnter method, is written directly into the setup method. However, this means that the component is loaded and displayed first, then the code is executed and, if the check fails, the component is redirected to an error page, for example.
My idea was to make my check directly in the route configuration in the beforeEnter method of a route. However, I don't have access to the Pinia Store, which doesn't seem to be initialized yet, although it is called before in the main.js.
Console Log
Uncaught Error: [🍍]: getActivePinia was called with no active Pinia. Did you forget to install pinia?
const pinia = createPinia()
app.use(pinia)
This will fail in production.
Router.js
import { useProcessStore } from "#/store/process";
const routes: Array<RouteRecordRaw> = [
{
path: "/processes/:id",
name: "ProcessView",
component: loadView("ProcessView", "processes/"),
beforeEnter: () => {
const processStore = useProcessStore();
console.log(processStore);
},
children: [
{
path: "steer",
name: "ProcessSteer",
component: loadView("ProcessSteer", "processes/")
},
{
path: "approve/:code",
name: "ProcessApprove",
component: loadView("ProcessApprove", "processes/")
}
]
},
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
});
export default router;
main.js
import { createApp } from "vue";
import "#/assets/bundle-bootstrap.css";
import App from "#/App.vue";
import { createPinia } from "pinia";
import router from "#/router";
import SvgIcon from "#/components/SvgIcon.vue";
const pinia = createPinia();
const app = createApp(App);
app.use(pinia);
app.use(router);
app.component("SvgIcon", SvgIcon);
router.isReady().then(() => {
app.mount("#app");
});
However, I don't have access to the Pinia Store, which doesn't seem to be initialized yet, although it is called before in the main.js
Before what? Pinia instance is created with const pinia = createPinia(); after the router module is imported - while it is imported, all side-effects including the call to createRouter() are executed. Once the router is created it begins it's initial navigation (on client - on server you need to trigger it with router.push()) - if you happen to be at URL matching the route with guard that is using Pinia store, the useProcessStore() happens before Pinia is created...
Using a store outside of a component
You have two options:
either you make sure that any useXXXStore() call happens after Pinia is created (createPinia()) and installed (app.use(pinia))
or you pass the Pinia instance into any useXXXStore() outside of component...
// store.js
import { createPinia } from "pinia";
const pinia = createPinia();
export default pinia;
// router.js
import pinia from "#/store.js";
import { useProcessStore } from "#/store/process";
const routes: Array<RouteRecordRaw> = [
{
path: "/processes/:id",
name: "ProcessView",
component: loadView("ProcessView", "processes/"),
beforeEnter: () => {
const processStore = useProcessStore(pinia ); // <-- passing Pinia instance directly
console.log(processStore);
},
},
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
});
export default router;
// main.js
import { createApp } from "vue";
import App from "#/App.vue";
import store from "#/store.js";
import router from "#/router";
const app = createApp(App);
app.use(store);
app.use(router);
router.isReady().then(() => {
app.mount("#app");
});
Hope this would be helpful.
Vue provide support for some functions in which we need store(outside of the components).
To fix this problem I just called the useStore() function inside the function provided by Vue(beforeEach) and it worked.
Reference : https://pinia.vuejs.org/core-concepts/outside-component-usage.html
Example :
import { useAuthStore } from "#/stores/auth";
.
.
.
.
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
router.beforeEach(async (to, from) => {
const authStore = useAuthStore();
// use authStore Here
});
I have same problem to access the store in "beforeEach" method for managing authorization.
I use this method in main.js, not in router.js. in router.js store is not accessible.
create pinia instance in piniCreate.js
//piniaCreate.js
import { createPinia } from "pinia";
const pinia = createPinia();
export default pinia;
after that create my store in mainStore.js
import { defineStore } from 'pinia'
export const mainStore = defineStore('counter', {
state: () => {
return {
user: {
isAuthenticated: isAuthen,
}
}
},
actions: {
login(result) {
//...
this.user.isAuthenticated = true;
} ,
logOff() {
this.user.isAuthenticated = false;
}
}
});
Then I used beforeEach method in the main.js
//main.js
import { createApp } from 'vue'
import App from './App.vue'
import pinia from "#/stores/piniaCreate";
import { mainStore } from '#/stores/mainStore';
import router from './router'
const app = createApp(App)
.use(pinia)
.use(router)
const store1 = mainStore();
router.beforeEach((from) => {
if (from.meta.requiresAuth && !store1.user.isAuthenticated) {
router.push({ name: 'login', query: { redirect: from.path } });
}
})
app.mount('#app');
You can pass the method in the second parameter of definestore:
store.js
export const useAppStore = defineStore('app', () => {
const state = reactive({
appName: 'App',
appLogo: ''
})
return {
...toRefs(state)
}
})
router.js
router.beforeEach((to, from, next) => {
const apppStore = useAppStore()
next()
})
I have resolved this by adding lazy loading
const routes = [
{
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')
}
]

Cannot read matched of undefined when using router file

So I have a simple router file, that imports different routes for different parts of my website, so:
general.js (one of my route files)
import Home from '../../components/home/home'
const routes = [{
name: 'home',
path: '/',
component: Home
}]
export default routes
router.js
import Vue from 'vue'
import Router from 'vue-router'
import GeneralRoutes from './general'
Vue.use(Router)
const routes = Array.prototype.concat(
GeneralRoutes
)
const router = new Router({
mode: 'history',
routes
})
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
next({replace: true, name: 'login'})
}
next()
})
export default router
That is my router, now in my app.js, I simply use it like so:
import Vue from 'vue'
import Router from './core/routes/router'
new Vue({
el: '#app',
data: () => ({
user: ''
}),
Router,
});
But this is throwing an error saying the following:
[Vue warn]: Error in render: "TypeError: Cannot read property
'matched' of undefined"
When I console.log the router, I get the following:
router is lowercase
import Vue from 'vue'
import Router from './core/routes/router'
new Vue({
el: '#app',
data: () => ({
user: ''
}),
router: Router
});

VueJS: how array method `push` can be called on an object but still works?

In the following navigateToHome method, how is it possible to use Array's push method Array.prototype.push on an object ($router) where $router is the main router object:
user.vue
<script>
export default {
data() {
return {
id: this.$route.params.id
}
},
methods: {
navigateToHome(){
this.$router.push({path: '/'})
}
}
}
</script>
main.js - $router object is defined here
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import { routes } from './routes'
Vue.use(VueRouter);
const router = new VueRouter({
routes,
mode: 'history'
})
new Vue({
el: '#app',
router,
render: h => h(App)
})
Because it isn't the Array.prototype.push method, it's just a method to update the navigation history.
push (location: RawLocation, onComplete?: Function, onAbort?: Function) {
this.history.push(location, onComplete, onAbort)
}
Take a look at the source code:
https://github.com/vuejs/vue-router/blob/dev/src/index.js#L141
just pass a string instead of object. Have you tried: this?
this.$router.push('/')

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'})

Vue Router router-view error

I'm getting the following error when trying to implement vue-router.
Unknown custom element: <router-view> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
Where do I need to provide the name option?
A lot of the tutorials I'm looking at seem to be an older version of vue-router. I follow the set-up process but can't get it to work.
Might there be something special I have to do when using the webpack cli template?
I'm also using the vue-router cdn.
Here's my main.js
import Vue from 'vue'
import App from './App'
import ResourceInfo from '../src/components/ResourceInfo'
var db = firebase.database();
var auth = firebase.auth();
const routes = [
{ path: '/', component: App },
{ path: '/info', component: ResourceInfo }
]
const router = new VueRouter({
routes
})
/* eslint-disable no-new */
var vm = new Vue({
el: '#app',
components: { App },
created: function() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// Get info for currently signed in user.
console.log(user);
vm.currentUser = user;
console.log(vm.currentUser);
} else {
// No user is signed in.
}
})
// Import firebase data
var quizzesRef = db.ref('quizzes');
quizzesRef.on('value', function(snapshot) {
vm.quizzes = snapshot.val();
console.log(vm.quizzes);
})
var resourcesRef = db.ref('resources');
resourcesRef.on('value', function(snapshot) {
vm.resources.push(snapshot.val());
console.log(vm.resources);
})
var usersRef = db.ref('users');
usersRef.on('value', function(snapshot) {
vm.users = snapshot.val();
console.log(vm.users);
})
},
firebase: {
quizzes: {
source: db.ref('quizzes'),
asObject: true
},
users: {
source: db.ref('users'),
asObject: true
},
resources: db.ref('resources')
},
data: function() {
return {
users: {},
currentUser: {},
quizzes: {},
resources: []
}
},
router,
render: h => h(App)
})
And my App.vue
<template>
<div id="app">
<navbar></navbar>
<resource-info :current-user="currentUser"></resource-info>
<router-view></router-view>
</div>
</template>
<script>
import Navbar from './components/Navbar'
import ResourceInfo from './components/ResourceInfo'
export default {
name: 'app',
props: ['current-user'],
components: {
Navbar,
ResourceInfo
}
}
</script>
<style>
</style>
In your main.js file, you need to import VueRouter as follows:
import Vue from "vue" // you are doing this already
import VueRouter from "vue-router" // this needs to be done
And below that, you need to initialize the router module as follows:
// Initialize router module
Vue.use(VueRouter)
Other than the above, I cannot find anything else missing in your code, it seems fine to me.
Please refer to the installation page in docs, under NPM section:
http://router.vuejs.org/en/installation.html
First install vue router by using "npm install vue-route" and follow the bellow in main.js
import Vue from 'vue'
import Router from 'vue-router'
import App from './App'
import ResourceInfo from '../src/components/ResourceInfo'
var db = firebase.database();
var auth = firebase.auth();
Vue.use(Router)
var router = new Router({
hashbang: false,
history: true,
linkActiveClass: 'active',
mode: 'html5'
})
router.map({
'/': {
name: 'app',
component: App
},
'/info': {
name: 'resourceInfo',
component: ResourceInfo
}
})
// If no route is matched redirect home
router.redirect({
'*': '/'
});
// Start up our app
router.start(App, '#app')
This might be solve your problem
You forgot to import vue-router and initialize VueRouter in main.js
import VueRouter from "vue-router"
Vue.use(VueRouter)