Go to Ba...">
美文网首页
Vue路由传参的两种方式

Vue路由传参的两种方式

作者: Jure_joe | 来源:发表于2020-05-28 15:11 被阅读0次
  • 第一种:以?进行拼接要传递的参数
    <router-link to="/bar?name=lisi">Go to Bar</router-link>
    页面中获取值的方式::this.$route.query.name
  • 第二种:按模式进行匹配
    参考官网即可
    模式:/foo/:name/:id,其中foo为路径名称,:name,:id为参数名称
    路径:/foo/zhangsan/4,其中zhangsan,4分别对应nameid的参数值
    页面获取值的方式this.$route.params.name
  • 代码示例
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
    </head>
    <style type="text/css">
        .m-enter,.m-leave-to{
            opacity: 0;
            transform: translateX(50px);
        }
        .m-enter-active,.m-leave-active{
            transition: all 0.8s ease;
        }
    </style>
    <body>
        <div id="app">
            <!-- <a href="#/foo">Go to Foo</a>
            <a href="#/bar">Go to Bar</a> -->
            <!-- 底层渲染为a链接 -->
            <!-- <router-link to="/foo?name=zhangsan">Go to Foo -->
            <!-- 直接跟参数的值 -->
            <router-link to="/foo/zhangsan/4">Go to Foo</router-link>&nbsp;&nbsp;
            <!-- 以问号进行参数传递 -->
            <router-link to="/bar?name=lisi">Go to Bar</router-link>
            
            <transition name='m' mode='out-in'>
                <router-view></router-view>
            </transition>
        </div>
        <template id="temp1">
            <div>
                这是第一个组件Foo-----{{msg}}
            </div>
        </template>
        <template id="temp2">
            <div>
                这是第二个组件Bar-----{{msg1}}
            </div>
        </template>
        <script type="text/javascript">
            const Foo = {
                template:'#temp1',
                data:function(){
                    return {
                        msg:this.$route.params.name,
                    }
                }
            }
            const Bar = {
                template:'#temp2',
                data:function() {
                    return {
                        msg1:this.$route.query.name
                    }
                }
            }
            /* 提醒一下,当使用路由参数时,例如从 /user/foo 导航到 /user/bar,原来的组件实例会被复用。因为两个路由都渲染同个组件,比起销毁再创建,复
            用则显得更加高效。不过,这也意味着组件的生命周期钩子不会再被调用。 */
            const routes=[
                /* 默认规则下的重定向 */
                { path: '/', redirect: '/foo/niusan/4' },
                { path: '/foo/:name/:id', component: Foo },
                { path: '/bar', component: Bar }
            ]
            const router = new VueRouter({
                routes
            });
            const vm = new Vue({
                router
            }).$mount("#app");
        </script>
    </body>
</html>

相关文章

网友评论

      本文标题:Vue路由传参的两种方式

      本文链接:https://www.haomeiwen.com/subject/kjhaahtx.html