1.路由和路由器的安装和创建
1)npm i vue-router -S
2) import Vue from "vue"
import VueRuter from "vue-router"
Vue.use(VueRouter)
3)首先在pages下面创建路由组件
引入路由组件
const routes = [
{path:"路径",component:组件}
]
4)创建路由 const router = new VueRouter({router,mode:"history",LinkActiveClass,LinkExactActiveClass})
将路由放入new Vue({router})
5)在组件中创建路由并写路由占位
<route-link to="路径"></route-link>
<route-view></route-view>
2.重定向
{path:"/",redirect:"地址"}
3.嵌套路由
{path:"/路径",
component:组件,
children:{
path:"路径",
component:组件
}
}
4.动态路由
定义形式:
1.独立使用(各个动态路由之间没有公共部分)
{
path:"/user/:id?",
component:user, //动态路由组件
}
2.和嵌套路由相结合(各个动态路由之间有公共部分)
{
path:"/user",
component:user, //公共部分
children: [
{
path:":id",
component:userInfo //动态路由组件
}
]
}
$route的抽象:(对url进行抽象)
$route.fullpath : 完整的路径
$route.path : 完整路径中的path部分+params部分
$route.params : 完整路径中的params部分
$route.query : 完整路径中的query部分
$route.hash : 完整路径中的hashy部分
组件的复用:
正常路由的切换;对应的路由组件都是销毁后重新创建并被加载的
当动态路由之间进行切换时; 对应的路由组件会被复用!
复用会导致对应组件的生命周期钩子不会执行;如果需要响应路由参数的变化;我们可以
watch $route
5.编程式导航
this.$router.push("字符串")
this.$router.push({
path,
query,
hash
})
当使用对象形式时;path和params不能同时出现;如果要使用params得使用命名路由
this.$router.push({
name,
params,
query,
hash
})
6.路由器配置 API
配置:
路由配置:path、component、redirect、name、children、props
路由器配置:routes、mode、LinkActiveClass、linkExactActiveClass
全局组件:
<route-link to="路径"></route-link>
<route-view></route-view>
Vue实例属性:
Vue.prototype.$route
$route.fullpath : 完整的路径
$route.path : 完整路径中的path部分+params部分
$route.params : 完整路径中的params部分
$route.query : 完整路径中的query部分
$route.hash : 完整路径中的hashy部分
Vue.prototype.$router
$router.push()