路由概念
- 理解: 一个路由(route)就是一组映射关系(key-value),多个路由需要路由器(router)进行管理
- 作用:设定访问路径,并将路径和组件映射起来(就是用于局部刷新页面,不需要请求服务器来切换页面)
配置
- 安装vue-router 全局配置 ,命令: npm i vue-router
- 或者使用cdn
<script src="https://unpkg.com/vue-router@3.0.0/dist/vue-router.js"></script>
路由的使用
- 由路由管理的地方 a标签转换成 router-link 标签 href=“相对路径” 变成 to=“路由路径”
- 要显示组件的地方需要用到 router-view占位
<body>
<div id="app">
<router-view></router-view>
</div>
<template id="index">
<div>
首页
<router-link to="/detail">去详情</router-link>
<button @click="todetail">去详情页函数式跳转</button>
</div>
</template>
<template id="detail">
<div>详情页详情页详情页详情页</div>
</template>
</body>
<script>
let index = {
template: "#index",
methods: {
todetail() {
this.$router.push({
path: "/detail",
quary: {
id: 12345,
},
});
},
},
};
let detail = {
template: "#detail",
created() {
console.log(this);
console.log(this.$route.query);
},
};
let chid = {
template: "#chid",
};
const router = new VueRouter({
routes: [
{
path: "/",
redirect: "/index",
},
{
path: "/index",
component: index,
},
{
path: "/detail",
component: detail,
children: [
{
path: "chid",
component: chid,
},
],
},
],
});
const vm = new Vue({
router,
el: "#app",
data: {},
methods: {},
});
</script>