How can I get query parameters from a URL in Vue.js?

后端 未结 9 1481
甜味超标
甜味超标 2020-12-12 13:47

How can I fetch query parameters in Vue.js?

E.g. http://somesite.com?test=yay.

Can’t find a way to fetch or do I need to use pure JS or some lib

相关标签:
9条回答
  • 2020-12-12 14:51

    You can get By Using this function.

    console.log(this.$route.query.test)
    
    0 讨论(0)
  • 2020-12-12 14:52

    According to the docs of route object, you have access to a $route object from your components, which exposes what you need. In this case

    //from your component
    console.log(this.$route.query.test) // outputs 'yay'
    
    0 讨论(0)
  • 2020-12-12 14:52

    Another way (assuming you are using vue-router), is to map the query param to a prop in your router. Then you can treat it like any other prop in your component code. For example, add this route;

    { 
        path: '/mypage', 
        name: 'mypage', 
        component: MyPage, 
        props: (route) => ({ foo: route.query.foo })  
    }
    

    Then in your component you can add the prop as normal;

    props: {
        foo: {
            type: String,
            default: null
        }
    },
    

    Then it will be available as this.foo and you can do anything you want with it (like set a watcher, etc.)

    0 讨论(0)
提交回复
热议问题