Imnotapotato
Imnotapotato

Reputation: 5808

How to fetch GET request variables with Vue (Router) before loading / displaying the page

When loading the login page - I want to check if there were GET variables set, and fetch them in my Vue app (So then I can change the mode displayed).

My URL and variables look like this:

https://localhost:3000/login?user=potato&token=666

my code looks like this:

let routes = [
    {
        path:       '/login',
        component:  Login
    },
    {
        path:       '/login/:user/:token',
        component:  Login,
        // props:   true
        props:      ['user', 'token']
    },
    ...
]; 

... ... ...

export default {
    props: [ 'user', 'token' ], 
    data() {
        return {
            // Change to yours for testing, empty these before production release
            user: '',
            pass: '',
            getData: null
        };
    },
    beforeRouteEnter (to, from, next) {
        getPost(to.params.id, (err, post) => {
            next(vm => vm.setGetData(err, post))
        })
    },
    // When route changes and this component is already rendered,
    // the logic will be slightly different.
    beforeRouteUpdate (to, from, next) {
        this.getData = null
        getPost(to.params.id, (err, post) => {
            this.setGetData(err, post)
            next()
        })
    },
    methods: {
        setGetData (err, post) {
            if (err) {
                this.error = err.toString()
            } else {
                this.getData = post
            }
        }
    }
}

My last try was trying to follow Vues documentation on fetching data: https://router.vuejs.org/guide/advanced/data-fetching.html#fetching-after-navigation

But it's not fully explained (getPost is not defined). I'm a bit new to Vue / VueRouter (I work with vanilla js or php), my question might seem basic but seriously, haven't found anything that represent a full well explained example of fetching get data.

I was told at the beggining that it's a "props" passing thing, and didn't get this right too, followed Vues doc: https://router.vuejs.org/guide/essentials/passing-props.html#boolean-mode

When handling this manually with window.location.href as suggested breaks my code:

    beforeRouteEnter(to, from, next) {
        console.log(window.location.href);
        if (this.getGetVariables(window.location.href)){
            console.log('has token: ' + this.token ); 
        }
        next()
    }, 

  methods: {
        // URL Variables: 
        getGetVariables: function(urlString) {
            var url = new URL(urlString);
            this.token = url.searchParams.get('token');
            console.log(this.token);
            if (!this.token) return false;
            this.user = url.searchParams.get('user');
            console.log(this.user);
        }

TypeError: Cannot read property 'getGetVariables' of undefined

Seems like it's not setting variables until it reaches create() (I think). So where am I suppose to save the URL variables?

I tried changing the beforeRouteEnter name to beforeRouteUpdate and it's not fetching the URL properly anymore in that function.

Upvotes: 3

Views: 5145

Answers (2)

tjeerddie
tjeerddie

Reputation: 46

You should be able to access the get query parameters with this.$router.query.


$route.query

type: Object

An object that contains key/value pairs of the query string. For example, for a path /foo?user=1, we get $route.query.user == 1. If there is no query the value will be an empty object.

source: https://router.vuejs.org/api/#route-object-properties


edit:

The user and token inside the path don't use the $router.query they are props that get filled by router and will automaticly change when the url changes.

https://router.vuejs.org/guide/essentials/passing-props.html

Here an example I found using ?name=value: https://jsfiddle.net/posva/chyLjpv0/

Here an example I found using /:name: https://jsfiddle.net/jonataswalker/ykf0uv0d/

Upvotes: 3

Radu Diță
Radu Diță

Reputation: 14171

Your approach with beforeRouteEnter is correct. You can access the get vars using vanilla JS using window.location.href.

I don’t know of any vue like method of getting the GET params.

Upvotes: 1

Related Questions