1. 程式人生 > 其它 >vue路由搭配以及巢狀路由的使用

vue路由搭配以及巢狀路由的使用

首先需要安裝vue-cli來構建一個vue的開發環境。

 然後我們在命令列中輸入npm install vue-router -g來安裝vue-router,安裝完之後我們可以開啟package.json檔案,在package.json檔案中可以看到vue-router的版本號。

 

 

 1.單頁面路由

 

 提前建好元件,我這在login裡面建了一個index.vue元件,引入到routes裡面來,

下面是跳轉路由的方式:

<router-link to="/Index">測試跳轉</router-link> this.$router.push('/Index') 
this.$router.push({path:'Index',query:{id: '1'}})     (頁面取參:this.$router.query.id)   2. 巢狀路由
簡單來說就是一個路由裡面包含n個子路由

 

 

3. 多個巢狀路由

運用場景一般都是一個介面出現多套模板,例如:一個首頁中有移動端和PC端。點擊出現各自的首頁

 

 遇到這種多個巢狀的話一般都要加   redirect  這個引數來預設當前主路由下面預設的子路由,

 

完整程式碼:

import Vue from 'vue' import Router from 'vue-router' import Index from '@/logo/Index' // app import appLogin from '@/app/Index' import appLoginIndex from '@/app/login/Index' // pc import pcLogin from '@/pc/Index' import pcLoginIndex from '@/pc/login/Index'
Vue.use(Router)
export default new Router({   routes: [     {       path: '/Index',       name: 'Index',       component: Index     },     {       path: '/',       name: 'pcLogin',       component: pcLogin,       redirect: 'pcLoginIndex',       children: [         {           path: '/',           name: 'pcLoginIndex',           component: pcLoginIndex,         }       ]     },     {       path: '/app',       name: 'app',       redirect: 'appIndex',       component: appLogin,       children: [         {           path: '/app/',           name: 'appIndex',           component: appLoginIndex,         }       ]     },   ] })   效果圖: