程式設計路由

m0_46069817發表於2020-10-13

程式設計路由

通過js程式碼使路由進行跳轉
$router.push()

$router.replace():和push相似,不同之處是不在history中加入新的記錄,而是替換當前的history記錄

$router.go(num)
num為負數時,表示後退num步
為正數時,表示前進幾步

$router.back():後退一步

$router.forward():前進一步

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./vue.js"></script>
    <script src="./vue-router.min.js"></script>
    <script>
        window.onload=function(){
            var student={
                template:`
                <div>
                    <h1>student-list</h1>
                </div>
                `
            };
            var teacher={
                created(){
                    alert(this.$route.query.id)
                },
                template:`
                <div>
                    <h1>teacher-list</h1>
                </div>
                `
            };
            var user={
                created(){
                    alert(this.$route.params.id)
                },
                template:`
                <div>
                    <h1>user-list</h1>
                </div>
                `
            };
            var router=new VueRouter({
                mode:"hash", //宣告當前路由的模式
                routes:[{
                    path:"/student",
                    component:student,
                },{
                    path:"/teacher",
                    component:teacher
                },{
                    path:"/user",
                    name:"user",
                    component:user
                }]
            });
            new Vue({
                el:"#app",
                router,
                methods:{
                    handler(){
                        this.$router.push("/student");
                        //console.log(history.length)
                    },
                    handler1(){
                        this.$router.push({path:'/teacher',query:{id:10}});
                    },
                    handler2(){
                        this.$router.push({name:'user',params:{id:11}});
                    },
                    back(){
                        this.$router.back();
                    },
                    forward(){
                        this.$router.forward();
                    },
                    go(){
                        this.$router.go(-1);
                    }
                }
            });
        }
    </script>
</head>
<body>
    <div id="app">
        <h1>程式設計路由</h1>
        <button @click="handler">student</button>
        <button @click="handler1">teacher</button>
        <button @click="handler2">user</button>

        <br>

        <button @click="back">back</button>
        <button @click="forward">forward</button>
        <button @click="go">go</button>

        <div>
            <router-view></router-view>
        </div>
    </div>
</body>
</html>

相關文章