VueJS | How can i get url parameters in vue.js? - javascript

Hi I'm making my own websites. and i'm newbie vue.js
I'm trying to get parameters to url.
I've been trying to any method. but not works.
Here is a url. -> example.com:8080/login
in this page, there's a button to register.
All i want is when i give url parameter(example.com:8080/login?id=hello&pw=1234), in login.vue, insert value -> user_id = hello, user_pw = 1234 and going back to exapmle.com:/8080
i'm trying to using vue.router. but it not works.
the error is
javax.servlet.ServletException: Circular view path [error]: would dispatch back to the current handler URL [/error] again. Check your ViewResolver setup!
and this is /router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Main from '../views/Main.vue'
import Login from '../views/Login.vue'
import Intro from '../views/Intro.vue'
import Info from '../views/Info.vue'
import Setting from '../views/Setting.vue'
import store from '../store'
import user_id from '../views/Login.vue'
import user_pw from '../views/Login.vue'
Vue.use(VueRouter)
const routes = [{
path: '/',
redirect: '/main',
},
{
path: '/login',
name: 'login',
component: Login,
},
{
path: '/signup',
name: '/signup',
component: SignUp
},
{
path: '/main',
component: Main,
beforeEnter(to, from, next) {
if (store.state.accessToken) {
next();
} else {
next('/login');
}
},
children: [{
path: '',
name: 'intro',
component: Intro,
},
{
path: '/info',
name: 'info',
component: Info,
},
{
path: '/setting',
name: 'setting',
component: Setting,
},
]
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: Login
});
var myApp = new Vue({
router,
el: '#app',
mounted: function() {
let parameters;
parameters = this.$route.query
console.log(parameters)
user_id = this.$route.query.id
user_pw = this.$route.query.pw
}
})
export default router
and this is part of login.vue
export default {
name: "test",
function() {
return {
id: "",
pw: "",
};
},
methods: {
test() {
axios.post("/login", {
id: this.userId,
pw: this.password
})
.then(function(response) {
if(response.data.code === 200) {
}
})
},
mounted : function() {
this.load();
}
}
i don't know what is wrong in my code.
my explain is too bad. sorry. but i'm trying to do my best

You are assigning routes to the Login component.
Replace
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: Login
});
with
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
});

"Hello world" example (Maybe it will be helpful). Click on the link to get utm_source:
const User = {
template: `<div><b>User:</b> {{ this.$route.params.id }} | <b>utm_source:</b>
{{this.$router.currentRoute.query['utm_source']}}</div>`
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
const app = new Vue({ router }).$mount('#app')
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<nav>
<router-link to="/user/foo?utm_source=facebook">Click her to see the utm_source=facebook of /user/foo?utm_source=facebook</router-link>
</nav>
<router-view></router-view>
</div>

Related

vue-router 4 '/:pathMatch(.*)*' not working?

hello guys I want to ask about vue-router.
when I use vue 2 if there is a page that doesn't match, I use path: '*' to go to my page404 but in vue 3 it's been replaced with '/:pathMatch(.)' after i tried it the warning in console disappeared but i just got a blank page and it doesn't point to my page404. did i miss something? I'm newbie with vue 3
here is the version I'm using:
vue: ^3.0.0
vue-router: ^4.0.0-0
and this is my index.js
import { createRouter, createWebHistory, RouterView } from 'vue-router'
const routes = [
{
path: '/',
redirect: '/login',
component: RouterView,
children: [{
path: '/login',
component: () => import('#/views/login/Login.vue'),
}]
},
{
path: '/:pathMatch(.*)*',
component: () => import('#/views/page404/Page404.vue')
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
You can try to write it like this
{
path: "/:pathMatch(.*)*",
redirect: "/404"
},
{
path: "/404",
name: "404",
component: () => import("#/views/page404/Page404.vue")
}

How to use vue-gapi plugin with router.js and router guards [duplicate]

This question already has an answer here:
Is there a way to accees vue js VueSession in main.js
(1 answer)
Closed 1 year ago.
I use a vue-gapi https://www.npmjs.com/package/vue-gapi in my code to access Google Calendar API. I was successful to install and use this plugin to get data from Calendar API. I now struggle to use router guards.
plugins/vuagapi.js:
import Vue from 'vue';
import VueGapi from 'vue-gapi';
const apiConfig = {
apiKey: '***',
clientId:
'***.apps.googleusercontent.com',
discoveryDocs: [
'https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest',
],
scope: 'https://www.googleapis.com/auth/calendar.readonly',
prompt: 'select_account',
};
Vue.use(VueGapi, apiConfig);
router/index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';
import Dashboard from '../views/Dashboard.vue';
import Login from '../views/Login.vue';
import '../plugins/vuegapi.js';
Vue.use(VueRouter);
const routes = [
{
path: '*',
redirect: '/',
},
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/login',
name: 'Login',
component: Login,
},
{
path: '/dashboard',
name: 'Dashboard',
component: Dashboard,
meta: {
authRequired: true,
},
},
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
});
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.authRequired)) {
if (this.$gapi.currentUser()) {
next();
} else {
alert('You must be logged in to see this page');
next({
path: '/login',
});
}
} else {
next();
}
});
export default router;
I am getting: vue-router.esm.js?8c4f:2314 TypeError: Cannot read property '$gapi' of undefined.
Anyone can point me to right direction? I am able to use this plugin in .vue files but not in another plain .js, suspecting that this $gapi exists only as Vue instakce property/method? As I am beginner I do not know how to import it properly.
if you wanna access Vue instance inside your router use router.app instead of this
change this line :
this.$gapi.currentUser()
to this:
router.app.$gapi.currentUser()
you can read more about Router Instance Properties in : https://router.vuejs.org/api/#router-instance-properties

Vue router doesn't recognize :lang as a param

I have the following code:
import Router from 'vue-router';
let mainRoutes = [
{path: '/first', component: () => import('./pages/First')},
{path: '/second', component: () => import('./pages/Second')},
{path: '/third', component: () => import('./pages/Third')},
];
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
scrollBehavior() {
return {x: 0, y: 0}
},
routes: [
{
path: '/:lang',
component: () => import('./layouts/Main'),
children: mainRoutes,
meta: {requiresAuth: true, permissions: true}
},
{
path: '*',
component: () => import('#/pages/errors/404')
}
]
})
router.beforeEach((to, from, next) => {
if (!to.query.lang) {
to.query.lang= 'ru';
next({ path: to.path, query: to.query });
} else {
next();
}
});
export default router
What I want:
Every time some route is entered, I want the vue-router to check whether it has the lang param or not. If not, I want it to place 'ru' in there, if yes then proceed and show the page with the necessary lang (the part which i18n is responsible for).
The problem is that it doesn't recognize ':lang' as a param for the children routes for some reason, so if I try to go to 'test.test/ru', it returns the lang param ok, but if I try 'test.test/ru/first' it doesn't see it and returns 404.
Everything works in case I put :lang param before every child component but it's not really practical. Is there any better way to solve this issue?
With a code like this you should get the effect you want.
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import VueRouter from 'vue-router';
import Router from './Router.vue';
import En from './translation/En.vue';
import Ru from './translation/Ru.vue';
Vue.use(VueI18n);
Vue.use(VueRouter);
Vue.use(VueBus);
const messages = {
en: En,
ru: Ru,
};
const i18n = new VueI18n({
fallbackLocale: 'ru',
locale: 'ru',
messages,
});
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/:lang',
component: {
render: (h) => h('router-view'),
},
children: [your children route],
});
router.beforeEach((to, from, next) => {
const { lang } = to.params;
if (!['en', 'fr'].includes(lang)) {
return next(i18n.locale);
}
if (i18n.locale !== lang) {
i18n.locale = lang;
}
return next();
});
I'm not sure but without i18n I think it's that :
...
router.beforeEach((to, from, next) => {
const { lang } = to.params;
if (!['en', 'ru'].includes(lang)) {
route.params.lang = 'ru';
router.push({ name: route.name });
}
});
I've finally found a solution!
If you have some param in the main route, your children routes shouldn't start with a '/' symbol, but simply with the correct route, for instance
let mainRoutes = [
{path: 'first', component: () => import('./pages/First')},
{path: 'second', component: () => import('./pages/Second')},
{path: 'third', component: () => import('./pages/Third')},
];
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
scrollBehavior() {
return {x: 0, y: 0}
},
routes: [
{
path: '/:lang',
component: () => import('./layouts/Main'),
children: mainRoutes,
meta: {requiresAuth: true, permissions: true}
},
]
})

Vue Router - Paths being concatenated multiple times

I am facing problems with the Vue Router and I have no idea what is causing this...
When my application loads it inserts the page path twice.
Example:
If I access the path http://localhost:8080/painel it will be shown in the browser the following path: http://localhost:8080/painel/painel
If I refresh the page the path will be added one more time, going like this: http://localhost:8080/painel/painel/painel
MY files:
/src/main.js
import Vue from 'vue'
import localforage from 'localforage'
import Notifications from 'vue-notification'
import App from './App'
import store from './store'
import router from './router'
import bus from './support/bus'
import http from './support/http'
Vue.config.productionTip = true
window._ = require('lodash')
localforage.config({
driver: localforage.LOCALSTORAGE,
storeName: 'invenio-center'
})
store.dispatch('auth/setToken').then(() => {
store.dispatch('auth/fetchSystemData').catch(() => {
store.dispatch('auth/clearAuth')
})
}).catch(() => {
store.dispatch('auth/clearAuth')
})
Vue.use(Notifications)
Vue.use(bus)
Vue.use(http)
new Vue({
el: '#app',
router,
store,
components: {App},
template: '<App/>'
})
/src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
import Login from '../pages/Login'
import Panel from '../pages/Panel'
import PanelIndex from '../pages/panel/Index'
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'login',
component: Login,
meta: {
visitor: true
}
},
{
path: 'painel',
component: Panel,
meta: {
auth: true
},
children: [
{
path: '/',
name: 'panel.index',
component: PanelIndex
},
{
path: 'idr',
name: 'panel.idr',
component: PanelIndex
}
]
},
{
path: "*",
redirect: {
name: 'panel.index'
},
component: PanelIndex
}
]
})
router.beforeEach(
(to, from, next) => {
store.dispatch('auth/setToken').then(() => {
if(to.meta.visitor){
next({
name: 'panel.index'
});
return;
}
next();
}).catch(() => {
if(to.meta.auth){
next({
name: 'login'
});
return;
}
next();
})
}
)
export default router
/src/pages/Panel.vue
<template>
<div class="panel-container">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'Panel',
data() {
return {
}
}
}
</script>
<style lang="scss" scoped>
.panel-container {
}
</style>
/src/pages/panel/Index.vue
<template>
<div class="index-container">index</div>
</template>
<script>
export default {
name: 'PanelIndex',
data() {
return {
}
}
}
</script>
<style lang="scss" scoped>
.index-container {
}
</style>
try this, add / before path: '/painel', and do that for other components.
/ is used to distinct from relative path.

How to pass app data to a VueRouter component

I am using VueRouter to load templates depending on the URL. When I try to use a property defined in app.data in the components, I receive a [VueWarn] Property or method "role" is not defined.
How can I pass every data property to the child components?
This is my script:
const Home = { template: '<p>home page, {{role}}</p>' }
const NotFound = { template: '<p>Page not found</p>' }
const routes = [
{path: '/', component: Home}
{path: '*', component: NotFound}
]
Vue.use(VueRouter)
var app = new Vue({
el: '#app',
data: {
role: 0,
cookiesAlert: true
},
router: new VueRouter({routes})
})
I think your router construction options are not set properly. Usually, I prefer to use 'named routes', therefore what I will set is:
const router = new VueRouter({
routes: [
{ name: 'role', path: '/:role', component: User },
{ path: '*', component: Home }
]
})
And if I don't understand your question wrong, what you want to do is pass the 'data' in parent components to child components via url and read the data in child component?
const User = {
template: '<div><br/>Role read from url is {{ $route.params.role }}</div>'
}
const Home = {
template: '<div><br/>Welcome</div>'
}
const router = new VueRouter({
routes: [
{ name: 'role', path: '/:role', component: User },
{ path: '*', component: Home }
]
})
new Vue({
router,
el: '#app',
data: {
role: 'default role'
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.2/vue-router.min.js"></script>
<div id="app">
The role is (Please change the 'role' value and click on '/User' link): <input v-model="role" type="text" /> <br/>
<router-link :to="{ name: 'role', params: { role: role }}">User</router-link>
<router-link to="/">Home</router-link>
<router-view></router-view>
</div>
Or if you don't want to use $route.params.role, what I will do is to set the 'props' in router config options to be true.
When props is set to true, the route.params will be set as the component props.
const router = new VueRouter({
routes: [
{ name: 'role', path: '/:role', component: User, props: true },
{ path: '*', component: Home }
]
})
And bind to the 'props' inside child components.
const User = {
props: ['role'],
template: '<div><br/>Role read from url is {{ role }}</div>'
}

Categories

Resources