vue構(gòu)建
import VueRouter from "vue-router";
Vue.use(VueRouter);
const routes = [{ path: "路徑",name: "名字",component:組件名}];
const router = new VueRouter({routes,mode: "history"});//mode設(shè)置后路徑不會(huì)出現(xiàn)/*/
new Vue({router,render: h => h(App)}).$mount("#app");
router-link實(shí)現(xiàn)跳轉(zhuǎn)
<router-link tag="li" class="nav-link" :to="{name:'HistaryLink'}">//router-link未設(shè)置tag時(shí)表示a標(biāo)簽,設(shè)置tag后表示為所設(shè)置的標(biāo)簽,所跳轉(zhuǎn)到頁(yè)面可用to直接表示,也可用:to用所設(shè)置name表示
$router事件跳轉(zhuǎn)
//跳轉(zhuǎn)到上一次瀏覽的頁(yè)面
this.$router.go(-1);
//指定跳轉(zhuǎn)的地址
this.$router.replace("/menu");
// 指定跳轉(zhuǎn)到路由名字下
this.$router.replace({ name: "menuLink" });
//通過(guò)push進(jìn)行跳轉(zhuǎn)
this.$router.push("/menu");
this.$router.push({ name: "menuLink" });
無(wú)用戶輸入地址時(shí)的默認(rèn)展示組件
const routes = [{ path: "*", redirect: "/" }];
或者
const routes = [{ path: "路徑",name: "名字",redirect: "默認(rèn)展示路徑",components:組件名}];
二級(jí)、三級(jí)路由
const routes = [{ path: "路徑",name: "名字",component:組件名,children[{path: "路徑",name: "名字",components:組件名}]}];
路由守衛(wèi)
全局守衛(wèi)
router.beforeEach((to, from, next) => {
//判斷登錄狀態(tài)store.gettes.isLogin === false
if (to.path == "/login" || to.path == "/register") {
next();
} else {
alert("還沒(méi)有登錄,請(qǐng)先登錄");
next("/login");
}
});
后置鉤子(不常用)
router.afterEach((to, from) => {
alert("after each");
});
路由獨(dú)享守衛(wèi)(設(shè)置在routes中)
beforeEnter: (to, from, next) => {
alert("非登錄狀態(tài)不能訪問(wèn)此頁(yè)面");
next(false);
//判斷登錄狀態(tài)store.gettes.isLogin === false;
if (to.path == "/login" || to.path == "/register") {
next();
} else {
alert("還沒(méi)有登錄,請(qǐng)先登錄");
next("/login");
}
}
組件內(nèi)守衛(wèi)(設(shè)置在對(duì)應(yīng)組件script中)
//組件內(nèi)守衛(wèi)beforeRouteEnter和beforeRouteLeave方法
beforeRouteEnter: (to, from, next) => {
// alert("hello" + this.name); //這樣name值找不到 因?yàn)槭窍燃虞d組件內(nèi)守衛(wèi)再加載data數(shù)據(jù)的
// next();
next(vm => {
alert("Hello" + vm.name); //想要獲取數(shù)據(jù)需要用這種形式
});
}
beforeRouteLeave: (to, from, next) => {
if (confirm("確定離開(kāi)嗎") == true) {
next();
} else {
next(false);
}
}
//beforeRouteEnter和beforeRouteLeave不能同時(shí)存在
復(fù)用router-view
const routes = [{ path: "路徑",name: "名字",components:{default:Home,orderringGuide: Orderring,delivery: Dellvery,
history: Histary}}];
<router-view name="orderringGuide"></router-view>//default表示默認(rèn)展示 剩余用這種形式展示
路由精簡(jiǎn)
創(chuàng)建routes.js文件
內(nèi)容為
1.引入的路由模塊路徑
2.export const routes = [{ path: "路徑",name: "名字",component:組件名}];
3.在main.js中引入routes.js文件import { routes } from "./routes";
路由控制滾動(dòng)行為
const router = new VueRouter({
routes,
mode: "history",
scrollBehavior(to, from, savedPosition) {
// return {
// x: 0,
// y: 100
// };
// return {selector:".btn"}
if (savedPosition) {
return savedPosition;
} else {
return { x: 0, y: 0 };
}
}
});