vue3:vue-router路由的使用各知识点简单案例代码

目录结构

//index.js

import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'

// import Home from "../pages/Home.vue";
// import About from "../pages/About.vue";

// 配置映射关系
const routes = [
  { 
    path: "/", 
    redirect: "/home" 
  },
  // /home/shops
  { 
    path: "/home", 
    name: "home",
    component: () => import(/* webpackChunkName: "home-chunk" */"../pages/Home.vue"),
    meta: {
      name: "why",
      age: 18,
      height: 1.88
    },
    children: [
      {
        path: "",
        redirect: "/home/message"
      },
      {
        path: "message",
        component: () => import("../pages/HomeMessage.vue")
      },
      {
        path: "shops",
        component: () => import("../pages/HomeShops.vue")
      }
    ]
  },
  { 
    path: "/about",
    name: "about",
    component: () => import("../pages/About.vue") 
  },
  { 
    path: "/user/:username/id/:id",
    component: () => import("../pages/User.vue") 
  },
  {
    path: "/login",
    component: () => import("../pages/Login.vue")
  },
  {
    path: "/:pathMatch(.*)",
    component: () => import("../pages/NotFound.vue")
  }
];

// 创建一个路由对象router
const router = createRouter({
  routes,
  history: createWebHistory()
})

// 动态添加路由
const categoryRoute = {
  path: "/category",
  component: () => import("../pages/Category.vue")
}

// 添加顶级路由对象
router.addRoute(categoryRoute);

// 添加二级路由对象
router.addRoute("home", {
  path: "moment",
  component: () => import("../pages/HomeMoment.vue")
})


// 导航守卫beforeEach
let counter = 0;
// to: Route对象, 即将跳转到的Route对象
// from: Route对象, 
/**
 * 返回值问题:
 *    1.false: 不进行导航
 *    2.undefined或者不写返回值: 进行默认导航
 *    3.字符串: 路径, 跳转到对应的路径中
 *    4.对象: 类似于 router.push({path: "/login", query: ....})
 */
router.beforeEach((to, from) => {
  console.log(`进行了${++counter}路由跳转`)
  // if (to.path.indexOf("/home") !== -1) {
  //   return "/login"
  // }
  if (to.path !== "/login") {
    const token = window.localStorage.getItem("token");
    if (!token) {
      return "/login"
    }
  }
})


export default router

 

//App.vue

<template>
  <div id="app">
    <!-- props: href 跳转的链接 -->
    <!-- props: route对象 -->
    <!-- props: navigate导航函数 -->
    <!-- props: isActive 是否当前处于活跃的状态 -->
    <!-- props: isExactActive 是否当前处于精确的活跃状态 -->
    <router-link to="/home" v-slot="props" custom>
      <button @click="props.navigate">{{props.href}}</button>
      <button @click="props.navigate">哈哈哈</button>
      <span :class="{'active': props.isActive}">{{props.isActive}}</span>
      <span :class="{'active': props.isActive}">{{props.isExactActive}}</span>
      <!-- <p>{{props.route}}</p> -->
    </router-link>
    <router-link to="/about">关于</router-link>
    <router-link to="/user/kobe/id/111">用户</router-link>
    <router-link to="/category">分类</router-link>

    <button @click="jumpToAbout">关于</button>
    <button @click="forwardOneStep">前进一步</button>

    <router-view v-slot="props">
      <!-- <transition name="why"> -->
        <keep-alive>
          <component :is="props.Component"></component>
        </keep-alive>
      <!-- </transition> -->
    </router-view>
  </div>
</template>

<script>

import { useRouter } from 'vue-router'
import NavBar from './components/NavBar.vue'

export default {
  name: 'App',
  components: {
    NavBar
  },
  methods: {
    // jumpToAbout() {
    //   // router
    //   this.$router.push("/about")
    // }
  },
  setup() {
    const router = useRouter();

    const jumpToAbout = () => {
      // router.push("/about")
      // router.push({
      //   path: "/about",
      //   query: {
      //     name: "why",
      //     age: 18
      //   }
      // })
      // router.replace("/about")
    }

    const forwardOneStep = () => {
      router.go(1)
      // router.go(-1)
      // router.forward()
      // router.back()
    }

    return {
      jumpToAbout,
      forwardOneStep
    }
  }
}
</script>

<style>
  .why-active {
    color: red;
  }

  .why-enter-from,
  .why-leave-to {
    opacity: 0;
  }

  .why-enter-active,
  .why-leave-active {
    transition: opacity 1s ease;
  }
</style>
//main.js

import { createApp } from 'vue'
import router from './router'
import App from './App.vue'

const app = createApp(App)

app.use(router)

app.mount('#app')

// createApp(App).use(router).mount("#app")
//login.vue

<template>
  <div>
    <button @click="loginClick">登录</button>
  </div>
</template>

<script>
  import { useRouter } from 'vue-router';

  export default {
    setup() {
      const router = useRouter();

      const loginClick = () => {

        window.localStorage.setItem("token", "why")

        router.push({
          path: "/home"
        })
      }

      return {
        loginClick
      }
    }
  }
</script>

<style scoped>

</style>
//user.vue

<template>
  <div>
    <h2>User: {{$route.params.username}}-{{$route.params.id}}</h2>
  </div>
</template>

<script>
  import { useRoute } from "vue-router";

  export default {
    created() {
      console.log(this.$route.params.username);
    },
    setup() {
      const route = useRoute();
      console.log(route.params.username);
    }
  }
</script>

<style scoped>

</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值