Home >Web Front-end >Vue.js >How to use vue-router in vue3
npm install vue-router@4.0.0-beta.13
Let’s first compare the difference between main.js in vue2 and vue3: ( The first picture is vue2, the second picture is vue3)
It can be clearly seen that the Vue objects we commonly use in vue2 , "disappeared" in vue3 due to the direct use of the createApp method, but in fact the app created using the createApp method is a Vue object. Vue.use(), which is often used in vue2, can be replaced by app in vue3 .use() is used normally; in the main.js file of vue3, use vue-router to directly call the router using the app.use() method.
Note: The route name exported by the import routing file is from "corresponding routing file relative path", the project directory is as follows (vue2 and vue3 are the same):
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
<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>
We introduce useRoute and useRouter where we need to use routing (equivalent to $route and $router in vue2)
<script> import { useRoute, useRouter } from 'vue-router' export default { setup () { const route = useRoute() const router = useRouter() return {} }, }</script>
Example: Page jump
<template> <h2>我是test1</h2> <button>toTest2</button> </template> <script> import { useRouter } from 'vue-router' export default { setup () { const router = useRouter() const toTest2= (() => { router.push("./test2") }) return { toTest2 } }, } </script> <style> </style>
The above is the detailed content of How to use vue-router in vue3. For more information, please follow other related articles on the PHP Chinese website!