VUE項(xiàng)目中引入vue-router的詳細(xì)過程
1、初識(shí) vue-router
vue-router 也叫 vue 路由,根據(jù)不同的路徑,來執(zhí)行不同的組件
2、安裝 vue-router
npm install vue-router
就會(huì)發(fā)現(xiàn),在 package.json 文件中,增加了如下內(nèi)容:
"dependencies": {
"vue-router": "^3.6.5"
},表示安裝成功
3、引入 vue-router
1、router/index.js 文件
在 src 目錄下新建 router 目錄,并在 router 目錄下新建一個(gè) index.js 文件
src/router/index.js
文件內(nèi)容如下:
import Vue from 'vue'
import Router from 'vue-router'
import Demo1 from '../components/Demo1'
Vue.use(Router);
// 設(shè)置組件映射規(guī)則
const routes = [
{
path: "/",
redirect: "/demo1"
},
{
path: '/demo1',
component: Demo1
}, {
path: '/demo2',
component: (resolve) => require(['@/components/Demo2'], resolve)
}
]
export default new Router({
routes
})- 可以通過 redirect 來實(shí)現(xiàn)重定向,我們將默認(rèn)路由重定向到 demo1
- 展示了兩種組件引入方式:
1、import Demo1 from ‘…/components/Demo1’
2、component: (resolve) => require([‘@/components/Demo2’], resolve)
2、main.js 文件
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
router
}).$mount('#app')引入我們創(chuàng)建的 router/index.js 文件,并將它掛載到我們的 vue 實(shí)例上
3、App.vue
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
<router-view/>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
}
}
</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>即根據(jù)路由映射出的組件將會(huì)在 router-view 標(biāo)簽內(nèi)展示
<router-view/>
4、Demo1.vue
<template>
<div>這是 demo1.vue</div>
</template>
<script>
export default {
name: "Demo1"
}
</script>
<style scoped>
</style>4、訪問路由
http://localhost:8080

可以看到 Demo1.vue 組件被加載,路由也被重定向到:
http://localhost:8080/#/demo1
到此這篇關(guān)于VUE項(xiàng)目中引入vue-router的文章就介紹到這了,更多相關(guān)vue引入vue-router內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- vue性能優(yōu)化之cdn引入vue-Router的問題
- vue系列之requireJs中引入vue-router的方法
- 使用vue3.x+vite+element-ui+vue-router+vuex+axios搭建項(xiàng)目
- 淺談vue項(xiàng)目4rs vue-router上線后history模式遇到的坑
- vue-router路由懶加載的實(shí)現(xiàn)(解決vue項(xiàng)目首次加載慢)
- vue 項(xiàng)目打包通過命令修改 vue-router 模式 修改 API 接口前綴
- 基于vue-cli vue-router搭建底部導(dǎo)航欄移動(dòng)前端項(xiàng)目
- 把vue-router和express項(xiàng)目部署到服務(wù)器的方法
相關(guān)文章
基于Vue3+Node.js實(shí)現(xiàn)大文件上傳功能
在 2025 年的 Web 開發(fā)浪潮中,大文件上傳已成為云存儲(chǔ),視頻平臺(tái)和多媒體應(yīng)用的剛需,本文我們就來使用 Vue?3 前端配合 Node.js 后端構(gòu)建一個(gè)支持秒傳和續(xù)傳的大文件上傳系統(tǒng)吧2025-07-07
如何解決sass-loader和node-sass版本沖突的問題
這篇文章主要介紹了如何解決sass-loader和node-sass版本沖突的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04
Vue3路由組件內(nèi)的路由守衛(wèi)onBeforeRouteLeave和onBeforeRouteUpdate使用
這篇文章主要介紹了Vue3路由組件內(nèi)的路由守衛(wèi)onBeforeRouteLeave和onBeforeRouteUpdate使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05

