展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

vue router入门(二)

  • 案例1:子路由
# app.js
var routes = [
    {
        path: '/user/:name',
        name: 'user',
        component: {
            template: `
            <div>
            <h3>我叫:{{$route.params.name}}</h3>
            <h3>我今年:{{$route.query.age}}岁了</h3>
            <router-link :to="'/user/' + $route.params.name + '/more'">更过信息</router-link>
            <router-view></router-view>
            </div>
            `
        },
        children: [
            {
                path: 'more',
                component: {
                    template: `
                    <div>
                    用户:{{$route.params.name}}的详细信息
                    more more more more more
                    </div> 
                    `
                }
            }
        ]
    },
]

var router = new VueRouter({
    routes: routes
})

# 01.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id ="app">
        <div>
            <router-link to="/user/王花花">王花花</router-link>
            <router-link to="/user/李栓蛋">李栓蛋</router-link>
        </div>
    </div>
    <script src="./vue.min.js"></script>
    <script src="./vue-router.js"></script>
    <script src="./app.js"></script>
</body>
</html>
  • 案例2:手动访问路由和传参
# app.js
new Vue({
    el: '#app',
    router: router,
    methods: {
        surf: function(){
            setTimeout(function(){
                this.router.push('/about')
                setTimeout(function(){
                    this.router.push({name: 'user',params: {name: '王花花'}})//路由对象需设置name
                })
            },2000)
        }
    }
})

# 01.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id ="app">
        <div>
            <router-link to="/user/王花花">王花花</router-link>
            <router-link to="/user/李栓蛋">李栓蛋</router-link>
        </div>
        <div>
            <router-view name="sidebar"></router-view>
        </div>
    </div>
    <script src="./vue.min.js"></script>
    <script src="./vue-router.js"></script>
    <script src="./app.js"></script>
</body>
</html>
posted @ 2022-09-08 14:01  DogLeftover  阅读(10)  评论(0编辑  收藏  举报