一、Vue路由配置
1、安装
npm install vue-router --save / cnpm install vue-router --save
2、引入vue-router并注册路由(以下步骤都在main.js里面)
import VueRouter from 'vue-router'
Vue.use(VueRouter);//注册路由
3、配置路由
(1)创建组件 引入组件
import Home from "./components/Home"
import Menu from "./components/Menu"
(2)定义路由
const routes = [
{path:"/",name:"home",component:Home},//默认显示
{path:"/menu",name:"menu",component:Menu},
{path:"*",redirect:"/"}//找不到路径返回默认路径,redirect设置默认路径
];
第(1)(2)两个步骤可以单独创建一个routes.js文件来存放
//routes.js
import Home from "./components/Home"
import Menu from "./components/Menu"
export const routes = [
{path:"/",name:"home",component:Home},//默认显示
{path:"/menu",name:"menu",component:Menu},
{path:"*",redirect:"/"}//找不到路径返回默认路径,redirect设置默认路径
];
//注意
//需要在main.js里面引入routes.js
//import { routes } from './routes'
(3)实例化VueRouter
const router = new VueRouter({
routes,//const声明的routes或者import引入的routes
mode:"history" //地址栏不显示'#'符号,hash模式改为history模式
})
(4)挂载
new Vue({
router, //挂载
el: '#app',
components: { App },
template: '<App/>'
})
二、跳转方法
//跳转到上一次浏览的页面
this.$router.go(-1);
//跳转到指定页面
this.$router.replace("/menu");
//指定路由的名字跳转
this.$router.replace({name:"menuLink"});
//通过push进行跳转
this.$router.push("/menu");
this.$router.push({name:"menuLink"});