首頁  >  文章  >  web前端  >  在Vue-Router2.X中實現多種路由實現

在Vue-Router2.X中實現多種路由實現

亚连
亚连原創
2018-06-06 16:03:131441瀏覽

下面我就為大家分享一篇Vue-Router2.X多種路由實現方式總結,具有很好的參考價值,希望對大家有幫助。

注意:vue-router 2只適用於Vue2.x版本,下面我們是基於vue2.0講的如何使用vue-router 2實現路由功能。

推薦使用npm安裝。

npm install vue-router

一、使用路由

在main.js中,需要明確安裝路由功能:

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
Vue.use(VueRouter)

1.定義元件,這裡使用從其他檔案import進來

import index from './components/index.vue'
import hello from './components/hello.vue'

2.定義路由

const routes = [
 { path: '/index', component: index },
 { path: '/hello', component: hello },
]

3.建立router 實例,然後傳routes 設定

const router = new VueRouter({
 routes
})

4.建立和掛載根實例。透過router 設定參數注入路由,讓整個應用程式都有路由功能

const app = new Vue({
 router,
 render: h => h(App)
}).$mount('#app')

經過上面的設定之後呢,路由符合的元件將會渲染到App.vue裡的f3c0d020f5c24a401c29efc656b14718dd6e4ababe59793a4ac75fb9e5c5550e

那麼這個App.vue裡應該這樣寫:


index.html里呢要这样写:

 

這樣就會把渲染出來的頁面掛載到這個id為app的p裡了。

二、重定向redirect

const routes = [
 { path: '/', redirect: '/index'},  // 这样进/ 就会跳转到/index
 { path: '/index', component: index }
]

三、巢狀路由

const routes = [
 { path: '/index', component: index,
  children: [
   { path: 'info', component: info}
  ]
  }
]

透過/index/info就可以存取到info元件了

四、懶載入

const routes = [
 { path: '/index', component: resolve => require(['./index.vue'], resolve) },
 { path: '/hello', component: resolve => require(['./hello.vue'], resolve) },
]

透過懶載入就不會一次性把所有組件加載進來,而是當你訪問到那個組件的時候才會加載那一個。對於元件比較多的應用程式會提高首次載入速度。

五、b988a8fd72e5e0e42afffd18f951b277

#在vue-router 2中,使用了b988a8fd72e5e0e42afffd18f951b2770e259af55a139990f31da244f503061c替換1版本中的a標籤


Home

Home

Home

Home

Home

User

Register

六、路由資訊物件

1.$route.path

字串,對應目前路由的路徑,總是解析為絕對路徑,如"/foo/bar"。

2.$route.params

一個 key/value 對象,包含了 動態片段 和 全匹配片段,如果沒有路由參數,就是一個空對象。

3.$route.query

一個 key/value 對象,表示 URL 查詢參數。例如,對於路徑 /foo?user=1,則有 $route.query.user == 1,如果沒有查詢參數,則是個空物件。

4.$route.hash

目前路由的 hash 值 (不含 #) ,如果沒有 hash 值,則為空字串。

5.$route.fullPath

完成解析後的 URL,包含查詢參數和 hash 的完整路徑。

6.$route.matched

一個數組,包含目前路由的所有巢狀路徑片段的 路由記錄 。路由記錄就是 routes 配置數組中的物件副本(還有在 children 數組)。

綜合上述,一個包含重定向、巢狀路由、懶載入的main.js如下:

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'
Vue.use(VueRouter)
const router = new VueRouter({
 routes:[
 { path: '/', redirect: '/index' },
 { path: '/index', component: resolve => require(['./components/index.vue'], resolve),
  children:[
   { path: 'info', component: resolve => require(['./components/info.vue'], resolve) }
  ]
 },
 { path: '/hello', component: resolve => require(['./components/hello.vue'], resolve) },
 ]
})
const app = new Vue({
 router,
 render: h => h(App)
}).$mount('#app')

上面是我整理給大家的,希望今後對大家有幫助。

相關文章:

整合vue到jquery/bootstrap專案方法?

在vue.js中實現分頁中點擊頁碼更換頁面內容

#在vue2.0元件中如何實作傳值、通信

以上是在Vue-Router2.X中實現多種路由實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:react專案開發下一篇:react專案開發