基礎(chǔ)入門(mén)文檔建議直接查看React中文文檔,這樣能少走很多彎路,
官方文檔地址:Vue Router
路由設(shè)置
router/index.js文件熬芜,管理路由器的創(chuàng)建:
import Vue from 'vue'
import Router from 'vue-router'
import Index from './views/index.vue' //直接加載
const Product = () => import('@/views/product.vue'); //懶加載
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Index ',
component: Index ,
},
{
path: '/product ',
name: 'Product ',
component: Product ,
},
]
})
路由跳轉(zhuǎn)
第一種使用方式:
<router-link to='/'>首頁(yè)</router-link>
<router-link to='/product'>子頁(yè)面</router-link>
第二種使用方式
this.$router.push('/')
this.$router.push('/product')
路由傳參
this.$router.push({ name: 'product', params: { userId: 123 }}) //類(lèi)似post傳參
this.$router.push({ path: 'product', query: { plan: 'private' }}) //類(lèi)似get傳參
History 模式
vue-router 默認(rèn) hash 模式 —— 使用 URL 的 hash 來(lái)模擬一個(gè)完整的 URL跛蛋,于是當(dāng) URL 改變時(shí)危尿,頁(yè)面不會(huì)重新加載示损。
如果不想要很丑的 hash,我們可以用路由的 history 模式犯眠,這種模式充分利用 history.pushState API 來(lái)完成 URL 跳轉(zhuǎn)而無(wú)須重新加載頁(yè)面按灶。
const router = new VueRouter({
mode: 'history',
routes: [...]
})
不過(guò)這種模式要玩好,還需要后臺(tái)配置支持筐咧。因?yàn)槲覀兊膽?yīng)用是個(gè)單頁(yè)客戶端應(yīng)用鸯旁,如果后臺(tái)沒(méi)有正確的配置,當(dāng)用戶在瀏覽器直接訪問(wèn)就會(huì)返回 404量蕊,這就不好看了铺罢。
所以呢,你要在服務(wù)端增加一個(gè)覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態(tài)資源残炮,則應(yīng)該返回同一個(gè) index.html 頁(yè)面韭赘,這個(gè)頁(yè)面就是你 app 依賴(lài)的頁(yè)面。這里只說(shuō)nginx的配置势就。
nginx的配置
location / {
try_files $uri $uri/ /index.html;
}
說(shuō)明:
這里root有兩種設(shè)置泉瞻,如果直接以www.xxxx.com/這種域名方式訪問(wèn)
location / {
root html/文件名;
}
如果直接以www.xxxx.com/admin/這種域名方式訪問(wèn)
location / {
root html;
}
不過(guò)前端路由的路徑就要改動(dòng),在每個(gè)路徑前面加上/admin
警告:
給個(gè)警告苞冯,因?yàn)檫@么做以后袖牙,你的服務(wù)器就不再返回 404 錯(cuò)誤頁(yè)面,因?yàn)閷?duì)于所有路徑都會(huì)返回 index.html 文件舅锄。為了避免這種情況鞭达,你應(yīng)該在 Vue 應(yīng)用里面覆蓋所有的路由情況,然后在給出一個(gè) 404 頁(yè)面皇忿。
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})