How do I retrieve URL parameters in Vue.js?

Hello, I am currently working on creating my own websites and I am new to vue.js. I am having trouble getting parameters from the URL. I have tried multiple methods but none seem to work. Here is an example URL: example.com:8080/login. On this page, there is a button to register. My goal is to be able to pass URL parameters (example.com:8080/login?id=hello&pw=1234) to the login.vue file and insert the values - user_id = hello, user_pw = 1234, then redirect back to example.com:/8080. I have been trying to use vue.router but it is not working. The error message I am receiving is:

javax.servlet.ServletException: Circular view path [error]: would dispatch back to the current handler URL [/error] again. Check your ViewResolver setup!

Here is a snippet of my /router/index.js file:

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',
    },
    /* Other route configurations */
]

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 here is a snippet of my login.vue file:

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 am not sure what is wrong with my code. My explanation may not be the best, but I am trying my hardest to figure it out.

Answer №1

The Login component is being assigned to the routes variable.

Instead of

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: Login
});

use

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
});

Answer №2

"Greetings, world!" demonstration (Possibly beneficial). Simply follow the link provided to retrieve utm_source:

const Individual = {
  template: `<div><b>Individual:</b> {{ this.$route.params.id  }} | <b>utm_source:</b> 
    {{this.$router.currentRoute.query['utm_source']}}</div>`
}

const routing = new VueRouter({
  routes: [
    { path: '/individual/:id', component: Individual }
  ]
})

const application = new Vue({ routing }).$mount('#application')
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="application">
  <nav>
    <router-link to="/individual/bar?utm_source=twitter">Simply click here to view the utm_source=twitter of /individual/bar?utm_source=twitter</router-link>
  </nav>
  <router-view></router-view>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve the IDs of selected items in jQuery selectables?

I have a straightforward question that I've been struggling to find an answer to. When using jQuery selectables, I want to retrieve the ID of the selected list item when it's clicked. Here is an example of my list: <ol id="selectable"> ...

What is the correct method for verifying the presence of a field in JavaScript (or its frameworks)?

Is there a better way to rewrite this computed method in JavaScript to handle cases where a field may not be available? computed() { isVerified() { return this.name.info.is_valid; } } I can make it less verbose, but I want it to still functi ...

Using the class for jQuery validation as opposed to the name attribute

I am looking to implement form validation using the jquery validate plugin, but I am facing an issue with using the 'name' attribute in the html since it is also used by the server application. Specifically, I want to restrict the number of check ...

Discovering the data-id value in an HTML element by clicking it with JavaScript and returning that value through a for loop

this is my unique html content <ul class="dialogs"> {% if t_dialogs %} <li class="grouping">Today</li> {% for item in t_dialogs %} <li class=&qu ...

Explore the extensive JSON link for redirecting

I have an issue with accessing the HATEOS link example on PayPal. My browser is showing a syntax error when I try to access the link. SyntaxError: missing ) after argument list [Break On This Error] alert(links.1.href); (line 32, col 15) The JSON d ...

What is the best way to test the validity of a form while also verifying email availability?

I am currently working on implementing async validation in reactive forms. My goal is to disable the submit button whenever a new input is provided. However, I am facing an issue where if duplicate emails are entered, the form remains valid for a brief per ...

Tips for formatting angular text sections

Within the scope of a controller, I have a status variable. After a successful rest PUT request, I add a message to this JavaScript variable. This message is displayed in my template using the {{status}} Is there a way to customize the styling of this mes ...

What are the compatibility considerations for npm packages with Angular 2? How can I determine which packages will be supported?

When working with Angular 2, do NPM packages need to be modified for compatibility or can any existing package work seamlessly? If there are compatibility issues, how can one determine which packages will work? For instance, let's consider importing ...

Using the "this" keyword is required for an Angular Service-created function

Although this question leans more towards JavaScript than Angular, I encountered an issue while creating a service. The function call looked like this: // controller injects activityApi , then service function call is made var activities = activityApi.get ...

Ajax is unintentionally duplicating the request

When the "async" parameter is set to "true", ajax sends two requests at the same time. But, when it is set to "false", there are no issues. To prevent the page from reloading, I am using the following code: $(document).ready(function() { $(document).on(& ...

Vuex - modify store state without changing the original object

Currently, I am encountering an issue where my attempt to duplicate a store object for local modification is causing the original store object to also be changed. The specific method I am using is ...mapState["storeObject"] To illustrate, here is a breakd ...

What are the steps to keep a web application from closing on Android when the back button is pressed?

I am currently working on a HTML5 web application and packaging it with Cordova (phonegap) 1.7. My goal is to customize the behavior of the Android back button so that instead of closing the application by default, it navigates back using window.history.b ...

What methods are recommended for expanding the size of a select/dropdown menu?

Managing a long list of values can be challenging, especially when it continues to grow. Consider the following example: <select> <option value="1">1, some test</option> <option value="2">2, some text</option> <optio ...

Is there a way to retrieve real-time information using momentjs in a Vue.js application without needing to refresh the

I have a unique table where I showcase details about a particular website. Among the displayed information is the timestamp indicating when the data was last updated. At the top of the table, my aim is to include an icon that will only appear if the dura ...

Guide on implementing file download and saving to the downloads directory in a Vue.js and Laravel 5.4 application

I am looking to make a button called View Resume that, when clicked by the user, will download the resume and store it in the downloads folder. The resume is currently stored in my table and I would like to be able to use vue.js to facilitate the download ...

Typescript: Verifying the type of an interface

In my code, I have a function called getUniqueId that can handle two different types of interfaces: ReadOnlyInfo and EditInfo. Depending on the type passed to this function, it will return a uniqueId from either interface: interface ReadOnlyInfo { item ...

"Trying to refresh your chart.js chart with updated data?”

Greetings! I have implemented a chart using chart.js and here is the corresponding code: let myChart = document.getElementById('myChart').getContext('2d'); let newChart = new Chart(myChart, { type: 'line', data: { labels: ...

Typehead.js on Twitter is displaying the full query instead of just the value

The Problem This is the issue I am facing with my code. My goal is to retrieve only the value, but instead of that, the entire query value is being returned. var engine; engine = new Bloodhound({ local: [{value: 'red'}, {value: 'blue&apo ...

Exploring the World of Observables within AngularJS

I've been experimenting with some exercises to grasp the inner workings of AngularJS, but I'm feeling a little lost at the moment. Despite scouring through the API, various documentation, and tutorials, I haven't quite found what I'm l ...

Refreshing data from firebase on each route change

I created an Angular service that retrieves items from Firebase using snapshotChanges and returns them. In my component, I subscribe to the data and store it in an array. I then display the data in cards using ngFor. However, whenever I navigate between p ...