Vue路由传参的两种方式

2020-05-28  本文已影响0人  Jure_joe
<!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>

上一篇 下一篇

猜你喜欢

热点阅读