Vue 路由 概念與基本使用
vue-router: vue的一個插件,專門來實現spa應用
關於spa應用的理解
單頁應用 single page application 整個應用只有一個完整的頁面
點擊頁面的導航,只會做局部更新
通過ajax請求數據
路由的理解
什么是路由
一個路由就是一組映射關系 key:value,key為路徑,value是function或Component
前端路由與后端路由
后端路由
value是function,用來處理客戶端的請求
即匹配請求路徑返回不同的數據
前端路由
value是Component,用來展示不同的內容
即匹配瀏覽器路徑展示不同的Component
路由的基本使用
安裝
npm i vue-router
配置routes
router/index.js
import VueRouter from 'vue-router'
import Island from '../components/Island'
import Polaris from '../components/Polaris'
export default new VueRouter({
routes:[
{
component:Island,
path:"/Island"
},
{
component:Polaris,
path:"/Polaris"
},
]
})
注冊插件
main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import router from './router'
// 關閉Vue的生產提示
Vue.config.productionTip = false
Vue.use(VueRouter)
// 創建Vue實例
new Vue({
// 將app組件放入容器中
render: h => h(App),
router
}).$mount('#app')
頁面使用
router-link:
- active-class 配置激活的路由樣式
- to 點擊之后要修改的路徑
router-view
- 匹配routes數組path,展示routes對應項的Component
- routes配置的component叫做路由組件,可用router-view標簽展示
app.vue
<template>
<div id="app">
<div class="nav">
<router-link class="nav" to="/Island" active-class="active-nav">
Island
</router-link>
<router-link class="nav" to="/Polaris" active-class="active-nav">
Polaris
</router-link>
</div>
<div class="con">
<router-view />
</div>
</div>
</template>
<script>
export default {
name: "App",
};
</script>
<style scoped>
#app {
display: flex;
width: 400px;
gap: 10px;
height: 100px;
}
.nav {
flex-basis: 100px;
display: flex;
flex-direction: column;
justify-content: flex-start;
}
.con {
flex-grow: 1;
background: rgb(126, 97, 143, 0.5);
}
.active-nav {
background: lightseagreen;
}
</style>
幾個注意點
routes里面配置的是路由組件,一般放在pages目錄里面,而一般組件放在component目錄下面
路由切換時,被隱藏的路由組件默認會被銷毀,需要的時候會再次掛載
每個路由組件都有自己的routes信息
整個應用只有一個$router