vue 路由动态路径传参、路由嵌套
1、路由动态路径传参
(1)使用
1、在路由路径中
routes: [
{ path: '/user/:id', ...}
]
混合路径传多个参数
/路径/:键名/路径/:键名
url中/路径/123/路径/223
同样能够通过第3步获取
2、传递路径参数
方式一:
在router-link跳转路径中
<router-link to='/user/值'><router-link>
方式二:
this.$router编程式跳转时传入
如:
this.$router.push('/detail/123')
this.$router.push({ name:'user',params: {id: 123 } })
3、获取路径参数
this.$route.params.id
(2)监听路径参数的变化:
当使用路由参数时,例如从/user/foo导航到/user/bar,原来的组件实例会被复用。意味着组件的生命周期钩子不会再被调用。
想对路由参数的变化作出响应的话,你可以简单地watch(监测变化)$route对象:
watch: {
$route(to, from) {
...
}
}
或路由守卫:
beforeRouteUpdate(to, from, next) {
...
next();
}
2、嵌套路由
1、在父路由中,与component同级,添加
children:[{
path:'不加/的和不加父级路径的名称',
component:子组件
}]
其中:
(1)多重子路由,在children中再添加children,设置
方式重复步骤,不要忘了给子路由设置子字路由的显示位置
children:[{xxx,children:[{xxx}]}]
(2)多个同级子路由,children[{xxx},{xxx},xxx]
2、在父路由的组件中设置给子路由的组件显示位置
<router-view />
3、在父路由的组件中,设置子路由跳转标签
此时的路径包括父路径
<router-link to='/父路径/子路径'></router-link>
代码示例:
路由js文件:
import Vue from 'vue'
import VueRouter from 'vue-router'
import HelloWorld from '../components/HelloWorld'
import C from '../components/C'
import D from '../components/D'
import A from '../components/A'
import B from '../components/B'
Vue.use(VueRouter)
export default new VueRouter({
routes:[
{
path:'/hello',
name:"HelloWorld",
component:HelloWorld
},
{
path:'/c',
name:'C',
component:C,
//子路由
children:[
{
path:'cc',
component:A,
//子子路由
children:[
{
path:'ccc',
component:A
}
]
}
]
},
{
path:'/d/:name',
name:'D',
component:D,
//子路由
children:[{
path:"dd",
component:B
}]
}
]
})
主入口文件:
<template>
<div id="app">
<img src="./assets/logo.png">
<ul>
<router-link to='/d/jeff'>d</router-link>
<router-link to='/c'>c</router-link>
</ul>
//主路由的显示
<router-view />
</div>
</template>
<script>
import Vuedemo from './components/Vuedemo'
import Vue1 from './components/Vuee'
import A from './components/A'
import B from './components/B'
import D from './components/D'
export default {
name: 'App',
data()
{
return{
}
},
methods:{
},
components: {
Vuedemo,
Vue1,
A,
B,
D
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
父路由组件:
<template>
<div>
ccc
<ul>
<router-link to="/c/cc">c的子路由</router-link>
</ul>
<router-view />
</div>
</template>
<script>
export default{
name:'c',
data()
{
return{
}
}
}
</script>
<style lang='css'>
</style>
父路由组件2:
<template>
<div>
ddd
<ul>
<router-link to="/d/dd">d的子路由</router-link>
</ul>
{ { this.$route.params.name}}
<router-view />
</div>
</template>
<script>
export default{
name:'d',
data()
{
return{
}
}
}
</script>
<style lang="css">
</style>
子组件:
<template>
<div>
子路由A
<ul>
<router-link to="/c/cc/ccc">子子路由</router-link>
</ul>
<router-view />
</div>
</template>
<script>
import B from './B'
export default{
name:'A',
data()
{
return{
}
}
}
</script>
<style lang='css'>
<style>
还没有评论,来说两句吧...