在Vue中,我们可以通过vue-router
路由管理页面之间的关系
Vue Router 是 Vue.js 的官方路由。它与 Vue.js 核心深度集成,让用 Vue.js 构建单页应用变得轻而易举
在Vue中引入路由
第一步:安装路由 npm install --save vue-router
第二步:配置独立的路由文件
import { createRouter,createWebHashHistory } from "vue-router"
import HomeView from "../views/HomeView"
import AboutView from "../views/AboutView"
// 配置信息中需要页面的相关配置
const routes = [
{
path:"/",
component:HomeView
},
{
path:"/about",
component:AboutView
}
]
const router = createRouter({
/**
* createWebHashHistory
* home:http://localhost:8080/#/
* about:http://localhost:8080/#/about
*
* 原理:a标签锚点连接
*/
/**
* createWebHistory
* home:http://localhost:8080/
* about:http://localhost:8080/about
* 此种方式,需要后台配合做重定向,否则会出现404问题
*
* 原理:H5 pushState()
*/
history:createWebHashHistory(),
routes
})
export default router;
第三步:引入路由到项目
// main.js
import router from './router'
app.use(router)
第四步:指定路由显示入口 <router-view/>
<template>
<!-- 路由的显示入口 -->
<router-link to="/">首页</router-link> |
<router-link to="/about">关于</router-link>
<router-view></router-view>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
#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;
}
</style>
第五步:指定路由跳转
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
页面不显示内容这个问题的解决方式有很多种,我这里只记录一下最让我们忽略的两点:
1.引用组件跳转时别忘了<router-view ></router-view>
这个一定要有,他是跳转的地方展示内容的,如果没有就不不知道跳转的页面内容放在那了
2.如果以上配置都没有问题,那么需要查看一下package.json
文件,查看router
相关插件本版好是否对应。
版本号不对应,vue本版2
,vue-router 版本4
,vuex本版4
,导致页面配置的路由内容不显示
。