vue3使用vue-router的完整步驟記錄
對于大多數(shù)單頁應(yīng)用程序而言,管理路由是一項(xiàng)必不可少的功能。隨著新版本的Vue Router處于Alpha階段,我們已經(jīng)可以開始查看下一個(gè)版本的Vue中它是如何工作的。
Vue3中的許多更改都會稍微改變我們訪問插件和庫的方式,其中包括Vue Router。
一、第一步:安裝vue-routernpm install vue-router@4.0.0-beta.13二、第二步: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. 利用CSS3新特性創(chuàng)建透明邊框三角2. html清除浮動的6種方法示例3. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)4. vue實(shí)現(xiàn)將自己網(wǎng)站(h5鏈接)分享到微信中形成小卡片的超詳細(xì)教程5. 不要在HTML中濫用div6. 使用css實(shí)現(xiàn)全兼容tooltip提示框7. 詳解CSS偽元素的妙用單標(biāo)簽之美8. JavaScript數(shù)據(jù)類型對函數(shù)式編程的影響示例解析9. CSS代碼檢查工具stylelint的使用方法詳解10. Vue3使用JSX的方法實(shí)例(筆記自用)
