本文主要和大家介绍vue router 动态路由和嵌套路由,详细的介绍了动态路由和嵌套路由的使用方法,有兴趣的可以了解一下,希望能帮助到大家。
首先介绍一下动态路由。
动态路由按照我的理解,就是说能够进行页面的跳转,比如说:下面的这个页面中:
/
/hello
/cc
如果点击了/hello,那么在router-view中就会加载对应的模块,也就是在路由中设置的模块。
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import Foo from '@/components/Foo'
import Foo2 from '@/components/Foo2'
import Foo3 from '@/components/Foo3'
Vue.use(Router)
export default new Router({
routes: [
{path: '/', redirect: '/hello'},
{
path: '/hello',
component: Hello,
children: [
{path: '/hello/foo', component: Foo},
{path: '/hello/foo2', component: Foo2},
{path: '/hello/foo3', component: Foo3}
]
},
{
path: '/cc',
name: 'Foo',
component: Foo
}
]
})
也就是说,会跳转到Hello和Foo这两个组件。
那么嵌套路由是什么意思呢,最开始我以为的是这样:/hello/foo 和/hello/foo2这两个路由可以简写成嵌套路由,其实不是的。嵌套路由只的是,在子组件中再次嵌套组件。然后在使用路由进行跳转,这样跳转的时候,变化的就只有子组件,而外边的父组件没有变化。
下面我把完整的例子放出来,看一下:
App.vue
/
/hello
/cc
export default {
name: 'app'
}
#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;
}
Foo.vue
3434234343
export default {
name: 'Foo',
data () {
return {
}
}
}
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
Foo2.vue
this is Foo2
export default {
name: 'Foo2',
data () {
return {
}
}
}
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
Foo3.vue
this is foo3
export default {
name: 'Foo3',
data () {
return {
}
}
}
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
Hello.vue
{{ msg }}
Essential Links
Ecosystem
/hello/foo
/hello/foo2
/hello/foo3
export default {
name: 'hello',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
路由:
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import Foo from '@/components/Foo'
import Foo2 from '@/components/Foo2'
import Foo3 from '@/components/Foo3'
Vue.use(Router)
export default new Router({
routes: [
{path: '/', redirect: '/hello'},
{
path: '/hello',
component: Hello,
children: [
{path: '/hello/foo', component: Foo},
{path: '/hello/foo2', component: Foo2},
{path: '/hello/foo3', component: Foo3}
]
},
{
path: '/cc',
name: 'Foo',
component: Foo
}
]
})
需要注意的是仔细的看App.vue和Hello.vue中,都包含,但是他们的作用不同,App.vue是顶层路由,指的是组外层的路由,Hello.vue中的是嵌套路由,负责显示子组件。
我把页面截图一下:
这个界面,点击最上边的 / 或者/hello 或者/cc的时候,发生变化的是红色路由中的内容。当点击/hello/foo /hello/foo2 /hello/foo3 的时候,发生变化的是下面蓝色路由中的内容。
这样就和我们平时应用十分的相似了。最外层于有变化,或者局部有变化,但是不想全局的发生改变。
同时,这样也符合了模块化,各个模块分别在不同的模块中。
相关推荐: