vue3使用vue-router的完整步驟記錄
對(duì)于大多數(shù)單頁(yè)應(yīng)用程序而言,管理路由是一項(xiàng)必不可少的功能。隨著新版本的Vue Router處于Alpha階段,我們已經(jīng)可以開始查看下一個(gè)版本的Vue中它是如何工作的。
Vue3中的許多更改都會(huì)稍微改變我們?cè)L問插件和庫(kù)的方式,其中包括Vue Router。
一、第一步:安裝vue-routernpm install vue-router@4.0.0-beta.13二、第二步:main.js
先來對(duì)比一下vue2和vue3中main.js的區(qū)別:(第一張為vue2,第二張為vue3)
可以明顯看到,我們?cè)趘ue2中常用到的Vue對(duì)象,在vue3中由于直接使用了createApp方法“消失”了,但實(shí)際上使用createApp方法創(chuàng)造出來的app就是一個(gè)Vue對(duì)象,在vue2中經(jīng)常使用到的Vue.use(),在vue3中可以換成app.use()正常使用;在vue3的mian.js文件中,使用vue-router直接用app.use()方法把router調(diào)用了就可以了。
注:import 路由文件導(dǎo)出的路由名 from '對(duì)應(yīng)路由文件相對(duì)路徑',項(xiàng)目目錄如下(vue2與vue3同):
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>四、使用(比如跳轉(zhuǎn))
我們?cè)谛枰褂寐酚傻牡胤揭雞seRoute 和 useRouter (相當(dāng)于vue2中的 $route 和 $router)
<script>import { useRoute, useRouter } from ’vue-router’export default { setup () { const route = useRoute() const router = useRouter() return {} },}
例:頁(yè)面跳轉(zhuǎn)
<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>總結(jié)
到此這篇關(guān)于vue3使用vue-router的文章就介紹到這了,更多相關(guān)vue3使用vue-router內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
