一叼架、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)創(chuàng)建組件 引入組件
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)兩個步驟可以單獨創(chuàng)建一個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"});