vue3如何使用vue-router

文章目录

  • 一、第一步:安装vue-router
  • 二、第二步:main.js
  • 三、路由文件
  • 四、app.vue
  • 四、使用(比如跳转)


一、第一步:安装vue-router

npm install [email protected]

二、第二步:main.js

先来对比一下vue2vue3main.js的区别:(第一张为vue2,第二张为vue3
vue3如何使用vue-router_第1张图片 vue3如何使用vue-router_第2张图片
可以明显看到,我们在vue2中常用到的Vue对象,在vue3中由于直接使用了createApp方法“消失”了,但实际上使用createApp方法创造出来的app就是一个Vue对象,在vue2中经常使用到的Vue.use(),在vue3中可以换成app.use()正常使用;在vue3的mian.js文件中,使用vue-router直接用app.use()方法把router调用了就可以了。

注:import 路由文件导出的路由名 from "对应路由文件相对路径",项目目录如下(vue2与vue3同):
vue3如何使用vue-router_第3张图片


三、路由文件

import { createRouter, createWebHashHistory } from "vue-router"

const routes = [
    {
        path: '/',
        component: () => import('@/pages')             
    },
    {
        path: '/test1',
        name: "test1",
        component: () => import('@/pages/test1')   
    },
    {
        path: '/test2',
        name: "test2",
        component: () => import('@/pages/test2')   
    },
]
export const router = createRouter({
  history: createWebHashHistory(),
  routes: routes
})

export default router

四、app.vue

<template>
  <router-view>router-view>
template>

<script>

export default {
  name: 'App',
  components: {
  }
}
script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
style>


四、使用(比如跳转)

我们在需要使用路由的地方引入useRouteuseRouter (相当于vue2中的 $route$router

<script>
import { useRoute, useRouter } from 'vue-router'
export default {
  setup () {
    const route = useRoute()
    const router = useRouter()
    return {}
  },
}

例:页面跳转

<template>
  <h1>我是test1</h1>
  <button @click="toTest2">toTest2</button>
</template>
<script>
import { useRouter } from 'vue-router'
export default {
  setup () {
    const router = useRouter()
    const toTest2= (() => {
      router.push("./test2")
    })
    return {
      toTest2
    }
  },
}
</script>
<style  scoped>
</style>

你可能感兴趣的:(vue3,工具类库,vue,vue.js)