温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue3中怎么使用vue-router

发布时间:2022-11-17 09:17:12 来源:亿速云 阅读:142 作者:iii 栏目:开发技术

这篇文章主要讲解了“vue3中怎么使用vue-router”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“vue3中怎么使用vue-router”吧!

一、第一步:安装vue-router

npm install vue-router@4.0.0-beta.13

二、第二步:main.js

先来对比一下vue2和vue3中main.js的区别:(第一张为vue2,第二张为vue3)

vue3中怎么使用vue-router 

vue3中怎么使用vue-router

可以明显看到,我们在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

三、路由文件

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>

四、使用(比如跳转)

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

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

例:页面跳转

<template>
  <h2>我是test1</h2>
  <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-router”的内容了,经过本文的学习后,相信大家对vue3中怎么使用vue-router这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI