vue 路由组件之间传递参数

2023-06-09  本文已影响0人  小黄不头秃
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <h1 >test</h1>
        <div>
            <router-link to="/user/1">user1</router-linnk>
            <router-link to="/user/2">user2</router-linnk>
            <router-link to="/user/3">user3</router-linnk>
        </div>
        <div>
            <router-view></router-view>
        </div>
    </div>

    <script src="./vue/vue.js"></script>
    <script src="./vue/vue-router.js"></script>
    <script>
        /**
        $route与路由高度耦合,不够灵活,所以可以使用props将组件和路由解耦
        1.props的值位布尔类型
        const router = new VueRouter({
            routes:{
                // 如果props被设置为true,route.params 将会被设置为组件属性
                {path:'/user/:id',component:user,props:true}
            }
        });

        const user = {
            props:['id'],//使用props接受路由参数
            template:'<div>用户:{{ id }}</div>'
        }
        2.props的值为对象类型(此时就不能够访问id)
        const router = new VueRouter({
            routes:{
                // 如果props被设置为true,route.params 将会被设置为组件属性
                {path:'/user/:id',component:user,props:{uname:"uname",age:12}}
            }
        });
        3,props的只为函数类型
        const router = new VueRouter({
            routes:[
                {
                    path:"/user/:id",
                    component:user,
                    props:route => ({uname:"zs",age:12,id:route.params.id})
                }
            ]
        })

        const user = {
            props:['uname','age','id'],
            template:'<div>用户信息:{{uname}}{{age}}{{id}}</div>'
        }
        */ 

        const user = {
            props:["id","uname","age"],
            template:"<h1>user{{ id }}组件,{{uname}},{{age}}</h1>"
        }
        // const router = new VueRouter({
        //     routes:[
        //         {
        //             path:"/",
        //             redirect:'/user'
        //         },
        //         {
        //             path:"/user/:id",
        //             component:user,
        //             props:true 
        //         }
        //     ]
        // });
        const router = new VueRouter({
            routes:[
                {
                    path:"/user/:id",
                    component:user,
                    props:route => ({uname:"zs",age:12,id:route.params.id})
                }
            ]
        })

        const vm = new Vue({
            el:"#app",
            router:router
        });
    </script>
</body>
</html>

上一篇下一篇

猜你喜欢

热点阅读