最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to fetch GET request variables with Vue (Router) before loadingdisplaying the page - Stack Overflow

programmeradmin1浏览0评论

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',
        ponent:  Login
    },
    {
        path:       '/login/:user/:token',
        ponent:  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 ponent 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: .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: .html#boolean-mode

  • How do I fetch the GET variables, before anything gets displayed so I have time to change the mode variable?

  • Does my URL look right? https://localhost:3000/login?user=potato&token=666 or should it look like this? https://localhost:3000/login/potato/666?

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.

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',
        ponent:  Login
    },
    {
        path:       '/login/:user/:token',
        ponent:  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 ponent 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/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/guide/essentials/passing-props.html#boolean-mode

  • How do I fetch the GET variables, before anything gets displayed so I have time to change the mode variable?

  • Does my URL look right? https://localhost:3000/login?user=potato&token=666 or should it look like this? https://localhost:3000/login/potato/666?

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.

Share Improve this question edited Mar 12, 2019 at 10:31 Imnotapotato asked Mar 12, 2019 at 9:28 ImnotapotatoImnotapotato 5,88814 gold badges86 silver badges156 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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/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/guide/essentials/passing-props.html

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

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

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.

发布评论

评论列表(0)

  1. 暂无评论