Vue路由机制--js跳转页面
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue路由机制--js跳转页面</title> </head> <body> <div id="app"> <router-link :to="{name:'user',params:{uid:11,uname:'U1'}}">User1</router-link> <router-link :to="{name:'user',params:{uid:22,uname:'U2'}}">User2</router-link> <router-link :to="{name:'user',params:{uid:33,uname:'U3'}}">User3</router-link> <router-link :to="{name:'user',params:{uid:44,uname:'U4'}}">User4</router-link> <router-link to="/reg">Reg</router-link> <router-view></router-view> </div> </body> <!-- 1.引入相关文件 --> <script type="text/javascript" src="js/vue.js"></script> <script type="text/javascript" src="js/vue-router.js"></script> <script type="text/javascript"> const User={ props:["uid","uname"], template:` <div> <h1>User组件--用户ID:{{uid}},姓名:{{uname}}</h1> <button @click="goRegister">跳转到注册页面</button> </div> `, methods:{ goRegister(){ console.log('点击跳转') //跳转 this.$router.push('/reg') //对象 this.$router.push({path:'/reg'}) //命名的路由(传递参数) this.$router.push({name:'User',params:{uid:123}}) //带查询参数 router.push({ path:'/reg',query:{uname:'lisi'} }) } } } const Reg={template: ` <div> <h1>Reg组件</h1> <button @click="goBack">回退页面</button> </div> `, methods:{ goBack(){ console.log('点击回退') //回退 this.$router.go(-1) } } } var router=new VueRouter({ routes:[ //为了更加方便的表示路由的路径.可以给路由规则起一个别名。 /* 即为“命名路由” */ { path:'/reg',component:Reg }, { //命名路由 name:'user', path:'/user/:uname',component:User,props:route=>({uname:route.params.uname,uid:route.params.uid}), } ] }) const vm=new Vue({ el:'#app', router:router,//挂载路由实例对象 }) </script> </html>