編程式路由導航
實例中定義一個方法,這個方法綁定在標簽上
然后就設置路由跳轉
語法 this.$router.history.push('要跳轉路由的地址')
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .active{ color:red; } </style> </head> <body> <div id="app"> <!--編程時導航--> <button @click="goHome">去首頁</button> <button @click="goList">去列表</button> <router-view></router-view> </div> </body> <script src="node_modules/vue/dist/vue.js"></script> <script src="node_modules/vue-router/dist/vue-router.js"></script> <script> let home={ template:'<div>home</div>' }; let list={ template:'<div>list</div>' } const routes=[ {path:'/home',component:home}, {path:'/list',component:list} ] let router=new VueRouter({ routes:routes, linkActiveClass:'active' }); //默認加載第一個路徑 router.push("/home"); let vm=new Vue({ el:"#app", methods:{ //編程時導航 goHome(){ //頁面跳轉,push是增加到歷史管理 this.$router.history.push('/home') //go表示前進后退 //this.$router.history.go(-1) }, goList(){ this.$router.history.push('/list') //將當前歷史管理替換成list //this.$router.history.replace('/list') } }, // 會在實例中提供兩個屬性this.$route(屬性),this.$router(方法); router:router, }) </script> </html>