创建组件
About.vue
<template>
<div>
<h2>this is about!</h2>
</div>
</template>
<script>
export default {
name: "About"
}
</script>
<style scoped>
</style>
Home.vue
<template>
<div>
<h2>this is home!</h2>
</div>
</template>
<script>
export default {
name: "Home"
}
</script>
<style scoped>
</style>
在Index.js中添加映射规则
import Vue from 'vue'
// 导入路由
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import home from '../components/Home'
import about from '../components/About'
// Vue加载
Vue.use(Router)
// 传入路由映射配置 导出路由实例
export default new Router({
routes: [
// {
// path: '/',
// name: 'HelloWorld',
// component: HelloWorld
// },
{
path: '/home',
name: 'home',
component:home
},
{
path: '/about',
name: 'about',
component:about
},
]
})
在App.vue中添加导航
通过router-view展示
<template>
<div id="app">
<!-- <img src="./assets/logo.png">-->
<!-- 导航链接-->
<router-link to="/home">主页</router-link>
<router-link to="/about">关于</router-link>
<!-- 用于展示组件-->
<router-view/>
</div>
</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>
效果
点击主页
点击关于
增加index.js的配置
// 在默认的情况下 重定向到主页
{
path: '',
redirect: "/home"
},
默认跳转的uri是使用的hash方式,这样会留下history历史记录,也就是说可以通过浏览器的左右箭头控制前后跳转,并且路径中间会有#号
如果不希望存在#,可以设置模式为history
// 设置模式为 history
mode: 'history',
如果不希望存在浏览记录History可以将to 改为replace