在实践过程中领悟的东西,才会记得更牢
router 为路由有hash与history两种模式
在vue中 有 router-link , router-view 为对应的视图
router-link的写法:
动态路由: 使用绑定的数据user/:id, 可以通过this.$router.id ,访问到对应路径的参数(使用:,相当于id成为一个参数,可以动态的改变)
但是动态路由的切换,
提醒一下,当使用路由参数时,例如从 /user/foo 导航到 /user/bar,原来的组件实例会被复用。因为两个路由都渲染同个组件,比起销毁再创建,复用则显得更加高效。不过,这也意味着组件的生命周期钩子不会再被调用。
如果要监听其变化,可以通过, 监听$router
达到目的, 或者使用守卫导航beforeRouteUpdate
const User = {
template: '...',
watch: {
'$route' (to, from) {
// 对路由变化作出响应...
}
}
}
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next()
}
}
嵌套路由
在嵌套的父组件中也是需要使用router-view展示相应的路由组件
这里不是很懂 以 / 开头的嵌套路径会被当作根路径。 这让你充分的使用嵌套组件而无须设置嵌套的路径
router-link, 中的to=" ", 实际等效于 this.$router.push;
当你点击 <router-link> 时,这个方法会在内部调用,所以说,点击 等同于调用 router.push(…)
当使用 this.$router.replace()的时候
在同级展示多个视图的时候,
此时router配置中的component 需要变为 components
rouer-view中也需要多个展示
这个的更加复杂:https://jsfiddle.net/posva/22wgksa3/
例子:
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<h1>Named Views</h1>
<ul>
<li>
<router-link to="/">/</router-link>
</li>
<li>
<router-link to="/other">/other</router-link>
</li>
</ul>
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
</div>
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
const Baz = { template: '<div>baz</div>' }
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/',
// a single route can define multiple named components
// which will be rendered into <router-view>s with corresponding names.
components: {
default: Foo,
a: Bar,
b: Baz
}
},
{
path: '/other',
components: {
default: Baz,
a: Bar,
b: Foo
}
}
]
})
new Vue({
router,
el: '#app'
})
路由组件传参: props, 进行解耦(这里不懂)
进阶:
路由守卫
三种,
- 一种是全局导航钩子:router.beforeEach(to,from,next),作用:跳转前进行判断拦截。
- 第二种:组件内的钩子;
- 第三种:单独路由独享组件