zheng 1 Minggu lalu
induk
melakukan
defec5663c

+ 40 - 14
vue/高阶/project2/src/router/index.js

@@ -13,30 +13,36 @@ import My from '../views/My.vue';
 // 路由表
 const routes = [
     {
-        path:'/',
+        path: '/',
         redirect: '/list'
     },
     {
-        path:'/home',
-        component: Home
+        path: '/home',
+        component: Home,
+        meta:{tip:"小提示"},
+        beforeEnter:(to,from,next) => {
+            console.log(to,'1')
+            next()
+        }
     },
     {
-        path:'/shop',
-        name:"shangpin",
+        path: '/shop',
+        name: "shangpin",
         component: Shop
     },
     {
-        path:'/my',
-        component: My
+        path: '/my',
+        component: My,
+        meta: { isAuth: true }
     },
     {
-        path:'/list',
+        path: '/list',
         component: List,
-        children:[
+        children: [
             {
                 // path:'detail',
-                path:'detail/:xxx',
-                name:'xiangqing',
+                path: 'detail/:xxx',
+                name: 'xiangqing',
                 props: true,
                 // 路由懒加载
                 component: () => import("../views/Detail.vue")
@@ -48,11 +54,31 @@ const routes = [
 // 定义路由表
 const router = new VueRouter({
     // 模式 history/hash
-    mode:'hash',
-    base:process.env.BASE_URL,
+    mode: 'hash',
+    base: process.env.BASE_URL,
     routes,
     // 全局配置高亮类
-    linkActiveClass:"active"
+    linkActiveClass: "active"
+})
+// 全局前置路由守卫:路由跳转前 登录鉴权 权限控制 路由拦截
+router.beforeEach((to, from, next) => {
+    // to 即将要进入的目标 路由对象
+    // from 当前导航正要离开的路由
+    // next 下一步
+    console.log(to, 'to')
+    if (to.meta.isAuth) {
+        if (localStorage.getItem("user")) {
+            next()
+        } else {
+           next("/shop")
+        }
+    } else {
+        next()
+    }
+})
+// 全局后置路由守卫:路由跳转后 修改页面标题 加载状态关闭 页面埋点
+router.afterEach((to,from) => {
+    document.title = to.meta.tip || 'vue项目' 
 })
 // 抛出路由表
 export default router;

+ 13 - 0
vue/高阶/project2/src/views/Shop.vue

@@ -1,5 +1,6 @@
 <template>
   <div class="shop">商场
+    <h1>请登录</h1>
       <button @click="goHome">去首页</button>
   </div>
 
@@ -10,6 +11,18 @@ export default {
   created() {
     console.log(this.$route)
   },
+  beforeRouteEnter(to,from,next) {
+    console.log(to,'ttttt')
+    if(localStorage.getItem("user")) {
+      next()
+    } else {
+      alert("该组件禁止进入")
+    }
+  },
+  beforeRouteLeave(to,from,next) {
+    console.log(to,from,'aasa')
+    next()
+  },
   methods:{
     goHome(){
       // this.$router.push({