1. 安装前端路由并保存到配置文件package.json中
在命令行输入命令 cnpm install vue-router --save
2. 编写main.js文件
import Vue from 'vue'
import App from './App'
import VRouter from 'vue-router' //引入vue-router库
import Apple from './components/apple'//把apple组件引入进来
import Bananer from './components/bananer'//把bananer组件引入进来
Vue.use(VRouter)//注册使用VRouter
//使用路由的时候实例化这个类
let router = new VRouter({
routers:[
{
path:'/apple',
component:Apple
},
{
path:'/bananer',
component:Bananer
}
]
})
new Vue({
el: '#app',
router: router,//两个单词相同这行可简写为“router,”
template: '<App/>',
components: { App }
})
3. 编写App.vue文件
<template>
<div id="app">
<img src="./assets/logo.png">
<router-view></router-view><!--这个是内置组件,不用声明,只要入口文件有router自然会映射到这里-->
</div>
</template>
<script>
import Hello from './components/Hello'
export default {
name: 'app',
components: {
Hello
}
}
</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>
4. 利用 router-view内置对象在浏览器地址切换路由
在浏览器输入http://localhost:8080/#/apple,看到以下内容
其中,#是vue处理html5路由的一个方式,可以接收浏览器向前向后的一个切换,加了#代表加了哈希,意味着没有使用html5的history功能。在高级浏览器下,可以在main.js将mode设置为history模式,如下所示
import Vue from 'vue'
import App from './App'
import VRouter from 'vue-router' //引入vue-router库
import Apple from './components/apple'//把apple组件引入进来
import Bananer from './components/bananer'//把bananer组件引入进来
Vue.use(VRouter)//注册使用VRouter
//使用路由的时候实例化这个类
let router = new VRouter({
mode:'history',
routes:[
{
path:'/apple',
component:Apple
},
{
path:'/bananer',
component:Bananer
}
]
})
new Vue({
el: '#app',
router: router,//两个单词相同这行可简写为“router,”
template: '<App/>',
components: { App }
})
把路由模式设置为history后,在浏览器直接输入http://localhost:8080/apple 会跳转到apple路由,输入 http://localhost:8080/bananer 会跳转至bananer路由,并可以通过浏览器的向前向后进行切换
5. 通过router-link内置对象在页内切换路由
修改App.vue文件
<template>
<div id="app">
<img src="./assets/logo.png">
<router-view></router-view><!--这个是内置组件,不用声明,只要入口文件有router自然会映射到这里-->
<router-link :to="{path:apple}">to apple</router-link>
<router-link :to="{path:bananer}">to bananer</router-link>
</div>
</template>
<script>
import Hello from './components/Hello'
export default {
name: 'app',
components: {
Hello
}
}
</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>
当点击to apple,页面跳转到apple路由,当点解to bananer,页面跳转到bananer路由