項目中使用vue的時候一定會用到路由,並且二級路由甚至三級路由的需求都是剛需的,當然,多級路由配置方法和二級路由的是一樣的,簡單講講二級路由的配置。
第一步:安裝路由生態
yarn add vue-router (也可以用npm)
第二步:配置一級路由
一、src靜態文件夾下新建router文件夾並在其里面新建一個index.js文件,引入vue-router
// 1、引入vue-router和vue import Router from 'vue-router' import Vue from 'vue' // 2、需要在vue中使用vue-router Vue.use(Router) //原理是內部調用了Router.install(Vue) //3、暴露出去 export default router;
二、在main.js主入口文件引入router實例
// 在main.js主入口文件引入router實例 import router from './router' // 實例化中用router(由於屬性值和屬性名相同簡寫為router) new Vue({ render: h => h(App), router // 就是為了讓每一個組件都可以訪問到路由相關的api($router/$route)(面試題) }).$mount('#app')
三、配置視圖組件
在src文件夾下新建views文件夾在其下面新建組件Flims.vue
<template> <div> <p>電影頁面</p> <p>輪播圖</p> <p>選項卡</p> </div> </template>
四、配置一級路由
// 在index.js里面引入引入Films組件 import Films from "@/views/Films" let routes = [ { path:"/films",// 配置路徑 component:Films // 映射的組件 } ] // 實例化 let router = new Router({ routes, }) // 這樣配置完,只會把路徑跳過去,Films組件不會被渲染到頁面上 // 所以在App.vue機構中加上 <!--router-view就可以用來渲染對應的路由組件--> <router-view></router-view> // 這樣就完成了一級路由的配置
五、配置二級路由
views下新建文件夾films下新建兩個Nowplaying.vue和ComingSoon.vue兩個文件
// 在index.js下引入這兩個組件 import Nowplaying from '@/views/films/Nowplaying' import ComingSoon from '@/views/films/ComingSoon' // 配置路由路徑和映射組件(在films里面添加children數組里嵌套對象配置路徑及映射組件) let routes = [ { path:"/films", component:Films, children:[// 需要配置二級路由了 { path:'/films/nowplaying', component:Nowplaying }, { path:'/films/comingsoon', component:ComingSoon } ] } ] // 然后在films組件里面添加router-view <!--通過router-view標簽規定Films的二級路由的視圖位置---> <router-view></router-view>
六、路由切換
通過聲明式導航的方式進行路由跳轉:<router-link to='地址'></router-link>
注:必須和to一起使用,否則會報錯
在這里封裝一個路由切換的組件
<template> <ul> <!-- <router-link to="/films" active-class="active" tag="li">電影</router-link> <router-link to="/cinema" active-class="active" tag="li">影院</router-link> <router-link to="/center" active-class="active" tag="li">中心</router-link> --> // 利用router-link方法完成路由切換,並結合v-for方法進行渲染,tag標簽給為li,添加key屬性更快的加載,動態添加active-class屬性 <router-link v-for="nav in navList" :key="nav.id" :to="nav.path" active-class="active" tag="li" >{{nav.title}}</router-link> </ul> </template> <script> export default { data () { return {// 數據 navList:[ {id:1,title:"電影",path:"/films"}, {id:2,title:"影院",path:"/cinema"}, {id:3,title:"個人中心",path:"/center"} ] } }, methods: { } } </script> <style lang="scss" scoped> .active{ color:orange } ul{// 定位到下面並且上下居中,li均分 position: fixed; bottom: 0; left:0; width:100%; height:50px; display:flex; li{ flex:1; text-align: center; line-height: 50px; } } </style>