vue动态添加路由获取不到query

请看代码 /UserProfile 本来是没有query参数的,我动态添加了,但是获取确是undefined ????

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
    <div id="app">
        <p>
            <router-link to="/UserHome">UserHome</router-link>
            <router-link to="/UserProfile">UserProfile</router-link>
            <button type="button" @click='addPath()'>添加一个路由</button>
            <button type="button" @click='getQuery()'>获取query</button>
      </p>
      <router-view></router-view>
    </div>
</body>
</html>

<script>
    const UserHome = { template: '<div>UserHome</div>' }
    const UserProfile = { template: '<div>UserProfile</div>' }
    const routes = [
        {
            path:'/UserHome',
            component:UserHome
        },
        {
            path:'/UserProfile',
            component:UserProfile,
        }
    ];
    const router = new VueRouter({
        routes
    })
    const app = new Vue({ 
        router ,
        methods:{
            addPath(){
                 router.push({
                    path:'/UserProfile',
                    query:{name:'123'}
                 })
            },
            getQuery(){
                console.log(router.query)
            }
        }
    }).$mount('#app')    

</script>

回答:

getQuery(){
  console.log(this.$route.query)
}

这样就获取到了

回答:

千万要注意,获取query 是this.$route.query 不是this.$router.query!!!

暂无评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注