vue 路由的基本使用
vue前端路由:路径和组件的映射关系
1.vue-router 基本使用
1.1 下载vue-router模块包
npm 安装
npm install vue-router
yarn 安装
yarn add vue-router
1.2 引入VueRouter
import VueRouter from 'vue-router'
1.3 使用Vue的use方法,全局注册RouterLink和RouterView的两个组件
Vue.use(VueRouter)
1.4 创建路由规则数组
import 组件对象 from 'vue文件路径'
const routes = [
{
path:"/路径名",
component:组件对象
}
]
1.5 用规则数组创建路由对象
const router = new VueRouter({
routes //属性名和值重复时,简写
})
1.6 把路由对象关联到Vue实例对象上
new Vue({
router //属性名和值重复时,简写
})
1.7 设置路由页面挂载点
<router-view></router-view>
2.声明式导航
-
router-link标签
好处:自带高亮类名
router-link-exact-acitve:(精准匹配) url中路由路径和a标签的herf一模一样才会添加这个类型(一处)
router-link-active:(模糊匹配)url中路由路径包含a标签的herf路径,就设置这个类名(多处)
-
声明式导航-传参
<router-link to="/路由路径?参数名=值"></router-link> // 方式1 <router-link to="/路由路径/值"></router-link> // 方式2
注意:方式2需要路由规则数组里提前埋伏好
const routes = [ { path:"/路由路径/:参数名", component:组件对象 } ]
-
声明式导航-接参
?参数名=值 就用
$route.query.参数名
(原地拿到了值)/路由路径/值 就用
$route.params.参数名
(原地拿到了对应值)
2.重定向
-
网页打开默认路由地址是:/
-
路由重定向
const routes = [ { path:"/", redirect:'/路由路径' } ]
3.404设置
-
在路由数组最后编写
const routes = [ // ...省略了其他对象 { path:"*", // 通配符-匹配任意的路由路径 component:404页面组件对象 } ]
4.路由模式
-
hash模式路由:http://xxxxxxx/#/路由路径
-
history模式路由:http://xxxxxx/路由路径(注意:上线以后需要后端服务器支持)
const router = new VueRouter({ mode:"history" // 默认不写就是"hash" })
5.编程时导航
js代码跳转路由
this.$router.push({
path:"/要跳转的路由路径", // 要给路由数组规则对应
name:"路由名字", // 路由规则数组对象上name属性定义路由名字
// 传参
query: {
参数名:值
},
params: {
参数名:值
}
})
// 路由规则
const routes = [
{
path:"/路由路径",
name:"路由名字"
}
]
// 注意: 使用path会忽略params
6.路由嵌套
-
创建二级路由vue文件(二级页面)
-
思考页面(要在哪个一级页面里嵌入这套2级路由系统)
-
路由规则里-添加children
const routes = [ { path:"/my", component:My, chidren:[ { path:"二级路径", component:二级页面组件 } ] }, { path:"/find", component:Find } ]
- 一级页面的vue 文件中写好router-view和导航链接
-