vue构建
import VueRouter from "vue-router";
Vue.use(VueRouter);
const routes = [{ path: "路径",name: "名字",component:组件名}];
const router = new VueRouter({routes,mode: "history"});//mode设置后路径不会出现/*/
new Vue({router,render: h => h(App)}).$mount("#app");
router-link实现跳转
//router-link未设置tag时表示a标签,设置tag后表示为所设置的标签,所跳转到页面可用to直接表示,也可用:to用所设置name表示
$router事件跳转
//跳转到上一次浏览的页面
this.$router.go(-1);
//指定跳转的地址
this.$router.replace("/menu");
// 指定跳转到路由名字下
this.$router.replace({ name: "menuLink" });
//通过push进行跳转
this.$router.push("/menu");
this.$router.push({ name: "menuLink" });
无用户输入地址时的默认展示组件
const routes = [{ path: "*", redirect: "/" }];
或者
const routes = [{ path: "路径",name: "名字",redirect: "默认展示路径",components:组件名}];
二级、三级路由
const routes = [{ path: "路径",name: "名字",component:组件名,children[{path: "路径",name: "名字",components:组件名}]}];
路由守卫
全局守卫
router.beforeEach((to, from, next) => {
//判断登录状态store.gettes.isLogin === false
if (to.path == "/login" || to.path == "/register") {
next();
} else {
alert("还没有登录,请先登录");
next("/login");
}
});
后置钩子(不常用)
router.afterEach((to, from) => {
alert("after each");
});
路由独享守卫(设置在routes中)
beforeEnter: (to, from, next) => {
alert("非登录状态不能访问此页面");
next(false);
//判断登录状态store.gettes.isLogin === false;
if (to.path == "/login" || to.path == "/register") {
next();
} else {
alert("还没有登录,请先登录");
next("/login");
}
}
组件内守卫(设置在对应组件script中)
//组件内守卫beforeRouteEnter和beforeRouteLeave方法
beforeRouteEnter: (to, from, next) => {
// alert("hello" + this.name); //这样name值找不到 因为是先加载组件内守卫再加载data数据的
// next();
next(vm => {
alert("Hello" + vm.name); //想要获取数据需要用这种形式
});
}
beforeRouteLeave: (to, from, next) => {
if (confirm("确定离开吗") == true) {
next();
} else {
next(false);
}
}
//beforeRouteEnter和beforeRouteLeave不能同时存在
复用router-view
const routes = [{ path: "路径",name: "名字",components:{default:Home,orderringGuide: Orderring,delivery: Dellvery,
history: Histary}}];
//default表示默认展示 剩余用这种形式展示
路由精简
创建routes.js文件
内容为
1.引入的路由模块路径
2.export const routes = [{ path: "路径",name: "名字",component:组件名}];
3.在main.js中引入routes.js文件import { routes } from "./routes";
路由控制滚动行为
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 };
}
}
});