VUE項目中引入vue-router的詳細(xì)過程
1、初識 vue-router
vue-router 也叫 vue 路由,根據(jù)不同的路徑,來執(zhí)行不同的組件
2、安裝 vue-router
npm install vue-router
就會發(fā)現(xiàn),在 package.json 文件中,增加了如下內(nèi)容:
"dependencies": {
"vue-router": "^3.6.5"
},表示安裝成功
3、引入 vue-router
1、router/index.js 文件
在 src 目錄下新建 router 目錄,并在 router 目錄下新建一個 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 來實現(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 實例上
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ù)路由映射出的組件將會在 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項目中引入vue-router的文章就介紹到這了,更多相關(guān)vue引入vue-router內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue使用vuedraggable實現(xiàn)嵌套多層拖拽排序功能
這篇文章主要為大家詳細(xì)介紹了vue使用vuedraggable實現(xiàn)嵌套多層拖拽排序功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04
vue實現(xiàn)導(dǎo)航欄效果(選中狀態(tài)刷新不消失)
這篇文章主要為大家詳細(xì)介紹了vue實現(xiàn)導(dǎo)航欄效果,選中狀態(tài)刷新不消失,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12
使用element-ui設(shè)置table組件寬度(width)為百分比
這篇文章主要介紹了使用element-ui設(shè)置table組件寬度(width)為百分比方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
分分鐘學(xué)會vue中vuex的應(yīng)用(入門教程)
本篇文章主要介紹了vue中vuex的應(yīng)用(入門教程),詳細(xì)的介紹了vuex.js和應(yīng)用方法,有興趣的可以了解一下2017-09-09

