安装路由vue
npm install vue-router
建立router.js与mian.js同级vue-router
router.js中的内容为npm
import Vue from 'vue' import Router from 'vue-router' //组件模块 import Home from './pages/home' import A from './components/a' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'home', component: Home }, { path: '/home', name: 'Home', component: Home }, { path: '/a', name: 'A', component: A}, ] })
在main.js中添加以下内容app
<template> <div id="app"> <router-view /> </div> </template> <script> export default { name: "app" }; </script> <style> </style>
就能够开始使用路由了,在须要使用路由的地方加入如下内容this
<router-link to="/">主页</router-link> //切换到指定的组件 <router-link to="/main">主页</router-link> <router-link to="/admin">管理页</router-link> <router-view/> //组件显示的地方
也可经过事件的方法来使用路由spa
methods:{ toMain() { this.$router.push('./main'); //跳转到指定组件 }, //使用路由返回上一级 goBack() { window.history.length > 1 ? this.$router.go(-1) : this.$router.push("/"); }, }