路由嵌套在路由配置里面对应嵌套的路由地下添加children数组,在数组里面添加嵌套的对象,此时路径path不用添加上一级的路径以及'/'直接加入路径既可:
path:'bases',
然后在对应的组件里添加跳转<router-link>,以及显示<router-view/>,来完成跳转显示,示例,在learn组件路由下嵌套base,
//路由配置
import Vue from 'vue'
import VueRouter from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Learn from '@/components/learn'
import Base from '@/components/base'
Vue.use(VueRouter)
export default new VueRouter({
routes:[{
path: '/xiao/:id',
name: 'Helloworld',
component:HelloWorld
},
{
path: '/lea',
name: 'Learn',
component:Learn,
children:[ //嵌套数组
{
path:'bases',
component:Base
}
]
}
]
})
//跳转组件
<template>
<div class="hello">
learn路由,^_^
<router-link to='/lea/bases'>基础</router-link>
<router-view/>
</div>
</template>
<script>
export default {
name: 'learn',
data () {
return {
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
//嵌套进的组件
<template>
<div class="hello">
学习vue基础知识
</div>
</template>
<script>
export default {
name: 'base',
data () {
return {
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
编程式导航:
编程式导航就是不用<router-link>来跳转,而是通过方法来跳转,vue提供了三种方法,this.$router.push this.$router.replace
this.$router.go
this.$router.push方法可以用参数形式,如this.$router.push(‘learn’)表示去learn页面,可以用对象参数this.$router.push({path:‘learn’})
this.$router.replace用法与this.$router.push相同,不同的是this.$router.replace方法不会留下历史记录,跳转后不能返回页面
this.$router.go方法的参数必须是整数,表示向前或向后跳参数步页面
写个第一个的例子,其他的不做示例:
<template>
<div id="app">
<img src="./assets/logo.png">
<ul>
<router-link to="/xiao/12345">luyou</router-link>
<router-link to="/lea">learn</router-link>
</ul>
<button type="button" @click="tiao">learn</button>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
components: {
},
methods:{
tiao(){
this.$router.push('/lea');
}
}
}
</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>
在示例中,点按钮learn和跳转标签learn是一样的效果