21.路由跳转
1. 路由跳转的4种方法:
方式一:router-link
//步骤一:设置路由(文件:/src/router/index.js) import Home from "@/components/Detail"; const routes = [ { path: "/detail", name: "detail", component: Detail } ] //步骤二:组件中使用(router-link跳转) //path: 有path,刷新页面id会保留。没有path,刷新页面后id会消。 //query:类似get,url里面会显示参数,刷新页面id还在。 //params类似post,url里面不会显示参数,刷新页面id消失。 <div> //刷新后id会消失 <router-link :to="{name:'detail'}">跳转</router-link> //刷新后id依然保留 <router-link :to="{path:'/detail'}">跳转</router-link> //url不会显示参数,刷新后id消失 <router-link :to="{name:'detail'},params:{id:1}">跳转</router-link> //url会显示参数,刷新后id还在 <router-link :to="{name:'detail',query:{id:1}}">跳转</router-link> </div> //步骤三:router-view渲染(文件:App.vue) <div id="app"> <router-view></router-view> </div>
方式二:this.$router.push()
//push:跳转到指定url后,history栈中添加一个记录,点击返回会跳转到上个页面 //不带参数 this.$router.push('/home') this.$router.push({name:'home'}) this.$router.push({path:'/home'}) //带参数 this.$router.push({name:'home',params: {id:1}}) //只能用name,刷新页面id消失 this.$router.push({name:'home',query: {id:1}}) //刷新页面id还在
方式三:this.$router.replace()
//replace:跳转到指定url后,history栈中不会有记录,点击返回会跳转到 上上 个页面 this.$router.replace()
方式四:this.$router.go(n)
//向前或者向后跳转n个页面,n可为正整数或负整数 this.$router.go(-1)
2. 动态组件:
//template <div> <div @click="changeCom">点击</div> <component :is="content"></component> </div> //script import Home from "@/components/Home"; import Detail from "@/components/Detail"; export default { components: { Home, Detail }, data(){ content:'Home' }, methods:{ changeCom(){ this.content="Detail" } } }
转载请注明原文链接:https://www.cnblogs.com/chenJieLing/