在vue3项目中快速引入vue-router

404 阅读1分钟

vue-router快速上手

安装依赖

install vue-router@4

创建router文件夹里面建index.js文件

/**
 * index.js
 * createRouter:创建一个可以被 Vue 应用程序使用的路由实例
 * mode: 'history' 配置已经被一个更灵活的 history 配置所取代。
 * 根据你使用的模式,你必须用适当的函数替换它:
 * "history": createWebHistory()
 * "hash": createWebHashHistory()
 * "abstract": createMemoryHistory()
 */
import { createRouter, createMemoryHistory ,createWebHistory} from "vue-router"

const router = createRouter({
  history: createWebHistory(),
  routes: [{
    path: '/',
    redirect:'/home',
    component: () => import('../components/Home.vue')
  }, {
    path: '/home',
    component: () => import('../components/Home.vue')
  }, {
    path: '/about',
    component: () => import('../components/About.vue')
  },]
})

export default router

main.js入口文件里面引用router/index.js

import { createApp } from 'vue'
import App from './App.vue'
// 引用router
import router from './router/index'
const app = createApp(App)

// 使用路由插件
app.use(router) // 就可以在各个组件里面使用router了
app.mount('#app')

在组件中使用

<template>
  <h1>
    about
  </h1>
  <button @click="toHome">click me</button>
</template>

<script setup>
// 因为我们在 setup 里面没有访问 this,所以我们不能再直接访问 this.$router 或 this.$route。作为替代,我们使用 useRouter 函数
import {useRouter,useRoute} from 'vue-router'
const router = useRouter()
const route = useRoute()

function toHome() {
  console.log(router,route);
  router.push('/home') // 跳转到home
}

</script>