vue3使用vue-router的完整步驟記錄
對于大多數(shù)單頁應(yīng)用程序而言,管理路由是一項(xiàng)必不可少的功能。隨著新版本的Vue Router處于Alpha階段,我們已經(jīng)可以開始查看下一個(gè)版本的Vue中它是如何工作的。
Vue3中的許多更改都會稍微改變我們訪問插件和庫的方式,其中包括Vue Router。
一、第一步:安裝vue-routernpm install [email protected]二、第二步:main.js
先來對比一下vue2和vue3中main.js的區(qū)別:(第一張為vue2,第二張為vue3)
可以明顯看到,我們在vue2中常用到的Vue對象,在vue3中由于直接使用了createApp方法“消失”了,但實(shí)際上使用createApp方法創(chuàng)造出來的app就是一個(gè)Vue對象,在vue2中經(jīng)常使用到的Vue.use(),在vue3中可以換成app.use()正常使用;在vue3的mian.js文件中,使用vue-router直接用app.use()方法把router調(diào)用了就可以了。
注:import 路由文件導(dǎo)出的路由名 from '對應(yīng)路由文件相對路徑',項(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))
我們在需要使用路由的地方引入useRoute 和 useRouter (相當(dāng)于vue2中的 $route 和 $router)
<script>import { useRoute, useRouter } from ’vue-router’export default { setup () { const route = useRoute() const router = useRouter() return {} },}
例:頁面跳轉(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)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. JSP servlet實(shí)現(xiàn)文件上傳下載和刪除2. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究3. ASP基礎(chǔ)知識VBScript基本元素講解4. React優(yōu)雅的封裝SvgIcon組件示例5. JavaWeb Servlet中url-pattern的使用6. 詳解瀏覽器的緩存機(jī)制7. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)8. jsp中sitemesh修改tagRule技術(shù)分享9. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼10. 輕松學(xué)習(xí)XML教程
