這篇文章是接著【三分鐘快速搭建Vue3+webpack項目】的內(nèi)容做的開發(fā),有基礎(chǔ)的可以跳過?【三分鐘快速搭建Vue3+webpack項目】,直接看以下的內(nèi)容。
Vue3的vue-router路由詳解:
首先安裝路由依賴模塊:
npm install vue-router@4
所需代碼文件如下圖:
圖1
?文章來源地址http://www.zghlxwxcb.cn/news/detail-429101.html
所需要的主要文件:index.html、index.js、App.vue
index.html:模板頁面,項目中的代碼編譯之后都是放入到模板頁面中id為app的元素這種。
代碼如下:
<!DOCTYPE html>
<html>
? <head>
? ? <meta charset="utf-8">
? ? <meta name="viewport" content="width=device-width,initial-scale=1.0">
? ? <title>Vue</title>
? </head>
? <body>
? ? <div id="app"></div>
? </body>
</html>
index.js:創(chuàng)建一個vue應(yīng)用,將路由放入應(yīng)用之中,并掛載到模板頁面id為app的元素上。
代碼如下:
import { createApp } from 'vue'
import { createRouter,createWebHashHistory } from 'vue-router'
import App from './App.vue'
// 1. 定義路由組件:這里直接用的對象數(shù)據(jù),也可以導(dǎo)入其他組件。
const Main = { render(){ return '月影WEB 歡迎大家來學(xué)習(xí)各種技術(shù)知識!'} }
const Lists = { render(){ return '月影WEB-列表頁面'} }
const Details = { render(){ return '月影WEB-詳情頁面'} }
// 2. 定義一些路由:每個路由都需要映射到一個組件。
const routes = [
? ? { path: '/', component: Main },
? ? { path: '/lists', component: Lists },
? ? { path: '/details', component: Details },
]
// 3. 創(chuàng)建路由實例并傳遞 `routes` 配置。
const router = createRouter({
? ? // 內(nèi)部提供了 history 模式的實現(xiàn)。為了簡單起見,我們在這里使用 hash 模式。
? ? history: createWebHashHistory(),
? ? routes, // `routes: routes` 的縮寫
})
// 4.創(chuàng)建一個vue應(yīng)用,將App組件和定義的路由放入到vue應(yīng)用,并掛載到模板頁面id為app的元素上。
createApp(App).use(router).mount('#app')
1. 定義路由組件:這里直接用的對象數(shù)據(jù),也可以導(dǎo)入其他組件。
const Main = { render(){ return '月影WEB 歡迎大家來學(xué)習(xí)各種技術(shù)知識!'} }
const Lists = { render(){ return '月影WEB-列表頁面'} }
const Details = { render(){ return '月影WEB-詳情頁面'} }
注意:Main、Lists 、Details 定義了三個路由組件,return后面就是每個路由組件展示的UI。
?
2. 定義一些路由:每個路由都需要映射到一個組件。
const routes = [
? ? { path: '/', component: Main },
? ? { path: '/lists', component: Lists },
? ? { path: '/details', component: Details },
]
注意:path是路由路徑,也是地址欄會顯示的路徑,component是放路由組件的,每個路由路徑都可以進行組件映射。
?
3. 創(chuàng)建路由實例并傳遞 `routes` 配置。
const router = createRouter({
? ? // 內(nèi)部提供了 history 模式的實現(xiàn)。為了簡單起見,我們在這里使用 hash 模式。
? ? history: createWebHashHistory(),
? ? routes, // `routes: routes` 的縮寫
})
注意:這里只做了簡單的配置,history是路由的模式,routes放定義的路由,createRouter創(chuàng)建路由實例。
?
4.創(chuàng)建一個vue應(yīng)用,將App組件和定義的路由放入到vue應(yīng)用,并掛載到模板頁面id為app的元素上。
createApp(App).use(router).mount('#app')
?
App.vue:用來展示不同的路由頁面UI。
代碼如下:
<template>
? ? <router-view></router-view>
</template>
<script>
export default {
}
</script>
注意:<router-view>是用來展示路由對應(yīng)的組件UI的。
?
啟動服務(wù)的效果如下:
{ path: '/', component: Main }
?
{ path: '/lists', component: Lists }
{ path: '/details', component: Details }
?
?
關(guān)注公眾號(月影WEB),了解更多的前后端知識;
歡迎大家關(guān)注互相交流學(xué)習(xí);文章來源:http://www.zghlxwxcb.cn/news/detail-429101.html
?
到了這里,關(guān)于Vue3的vue-router路由詳解的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!