淺談Vue.js路由管理器 Vue Router
起步
HTML
<script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <div id="app"> <h1>Hello App!</h1> <p> <!-- 使用 router-link 組件來導(dǎo)航. --> <!-- 通過傳入 `to` 屬性指定鏈接. --> <!-- <router-link> 默認(rèn)會(huì)被渲染成一個(gè) `<a>` 標(biāo)簽 --> <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> </p> <!-- 路由出口 --> <!-- 路由匹配到的組件將渲染在這里 n內(nèi)置組件--> <router-view></router-view> </div>
JavaScript
// 0. 如果使用模塊化機(jī)制編程,導(dǎo)入Vue和VueRouter,要調(diào)用 Vue.use(VueRouter)
// 1. 定義 (路由) 組件。
// 可以從其他文件 import 進(jìn)來
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
// 2. 定義路由
// 每個(gè)路由應(yīng)該映射一個(gè)組件。 其中"component" 可以是
// 通過 Vue.extend() 創(chuàng)建的組件構(gòu)造器,
// 或者,只是一個(gè)組件配置對(duì)象。
// 我們晚點(diǎn)再討論嵌套路由。
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
// 3. 創(chuàng)建 router 實(shí)例,然后傳 `routes` 配置
// 你還可以傳別的配置參數(shù), 不過先這么簡(jiǎn)單著吧。
const router = new VueRouter({
routes // (縮寫) 相當(dāng)于 routes: routes
})
// 4. 創(chuàng)建和掛載根實(shí)例。
// 記得要通過 router 配置參數(shù)注入路由,
// 從而讓整個(gè)應(yīng)用都有路由功能
const app = new Vue({
router
}).$mount('#app')
// 現(xiàn)在,應(yīng)用已經(jīng)啟動(dòng)了!
通過注入路由器,我們可以在任何組件內(nèi)通過 this.$router 訪問路由器,也可以通過 this.$route 訪問當(dāng)前路由:
export default {
computed: {
username () {
// 我們很快就會(huì)看到 `params` 是什么
return this.$route.params.username
}
},
methods: {
goBack () {
window.history.length > 1
? this.$router.go(-1)
: this.$router.push('/')
}
}
}
routes 選項(xiàng) (Array)
redirect(重定向 )
//此時(shí)訪問/a會(huì)跳轉(zhuǎn)到/b
const router = new VueRouter({
routes: [
{ path: '/a', redirect: '/b' }
]
})
//重定向的目標(biāo)也可以是一個(gè)命名的路由:
const router = new VueRouter({
routes: [
{ path: '/a', redirect: { name: 'foo' }}
]
})
//甚至是一個(gè)方法,動(dòng)態(tài)返回重定向目標(biāo):
const router = new VueRouter({
routes: [
{ path: '/a', redirect: to => {
// 方法接收 目標(biāo)路由 作為參數(shù)
// return 重定向的 字符串路徑/路徑對(duì)象
}}
]
})
命名路由
export default [
{
path:'/',
redirect:'/app' //默認(rèn)跳轉(zhuǎn)路由
},
{
path: '/app',
//路由命名,可用于跳轉(zhuǎn)
name: 'app',
}
]
//可用于跳轉(zhuǎn)
<router-link :to="{name:'app'}">app</router-link>
路由元信息
定義路由的時(shí)候可以配置 meta 字段:
export default [
{
path:'/',
redirect:'/app' //默認(rèn)跳轉(zhuǎn)路由
},
{
path: '/app',
//**相當(dāng)于HTML的meta標(biāo)簽**
meta: {
title: 'this is app',
description: 'asdasd'
},
}
]
嵌套路由
export default [
{
path:'/',
redirect:'/app' //默認(rèn)跳轉(zhuǎn)路由
},
{
path: '/app',
//子路由 匹配 /app/test
children: [
{
path: 'test',
component: Login
}
]
}
]
路由組件傳參
export default [
{
path:'/',
redirect:'/app' //默認(rèn)跳轉(zhuǎn)路由
},
{
path: '/app/:id', // /app/xxx ,組件內(nèi)部可以通過$route.params.id拿到這個(gè)值
// 會(huì)把:后面的參數(shù)通過props傳遞給組件Todozhong 中
//布爾模式
props: true,
//對(duì)象模式
props:{id:456}
//函數(shù)模式
props: (route) => ({ id: route.query.b }),
component: Todo,
}
]
mode選項(xiàng)(string)
vue-router 默認(rèn) hash 模式 —— 使用 URL 的 hash 來模擬一個(gè)完整的 URL,于是當(dāng) URL 改變時(shí),頁(yè)面不會(huì)重新加載。
如果不想要很丑的 hash,我們可以用路由的 history 模式,這種模式充分利用 history.pushState API 來完成 URL 跳轉(zhuǎn)而無須重新加載頁(yè)面。
const router = new VueRouter({
mode: 'history',
routes: [...]
})
這種模式要玩好,還需要后臺(tái)配置支持。
base(string)
應(yīng)用的基路徑。例如,如果整個(gè)單頁(yè)應(yīng)用服務(wù)在 /app/ 下,然后 base 就應(yīng)該設(shè)為 "/app/"
return new Router({
routes,
mode: 'history',//默認(rèn)使用hash#
base: '/base/', //在path前面都會(huì)加上/base/,基路徑
})
linkActiveClass(string)
默認(rèn)值: "router-link-active"
全局配置 <router-link> 的默認(rèn)“激活 class 類名”。
return new Router({
routes,
mode: 'history',//默認(rèn)使用hash#
base: '/base/', //在path前面都會(huì)加上/base/,基路徑
// 點(diǎn)擊calss名字
linkActiveClass: 'active-link', //匹配到其中一個(gè)子集
linkExactActiveClass: 'exact-active-link',//完全匹配
})
linkExactActiveClass(string)
默認(rèn)值: "router-link-exact-active"
全局配置 <router-link> 精確激活的默認(rèn)的 class。
scrollBehavior(Function)
路由跳轉(zhuǎn)后是否滾動(dòng)
export default () => {
return new Router({
routes,
mode: 'history',//默認(rèn)使用hash#
base: '/base/', //在path前面都會(huì)加上/base/,基路徑
//頁(yè)面跳轉(zhuǎn)是否需要滾動(dòng)
/*
to:去向路由,完整路由對(duì)象
from:來源路由
savedPosition:保存的滾動(dòng)位置
*/
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return { x: 0, y: 0 }
}
},
})
}
parseQuery / stringifyQuery (Function)
/每次import都會(huì)創(chuàng)建一個(gè)router,避免每次都是同一個(gè)router
export default () => {
return new Router({
routes,
mode: 'history',//默認(rèn)使用hash#
base: '/base/', //在path前面都會(huì)加上/base/,基路徑
// 路由后面的參數(shù)?a=2&b=3,string->object
parseQuery (query) {
},
//object->string
stringifyQuery (obj) {
}
})
}
fallback(boolean)
當(dāng)瀏覽器不支持 history.pushState 控制路由是否應(yīng)該回退到 hash 模式。默認(rèn)值為 true。
如果設(shè)置為false,則跳轉(zhuǎn)后刷新頁(yè)面,相當(dāng)于多頁(yè)應(yīng)用
<router-link>
過渡動(dòng)效
<router-view> 是基本的動(dòng)態(tài)組件,所以我們可以用 <transition> 組件給它添加一些過渡效果:
<transition> <router-view></router-view> </transition>
高級(jí)用法
命名視圖
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
const router = new VueRouter({
routes: [
{
path: '/',
components: {
//默認(rèn)組件
default: Foo,
//命名組件
a: Bar,
b: Baz
}
}
]
})
導(dǎo)航守衛(wèi)
全局守衛(wèi)
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './app.vue'
import './assets/styles/global.styl'
// const root = document.createElement('div')
// document.body.appendChild(root)
import createRouter from './config/router'
Vue.use(VueRouter)
const router = createRouter()
// 全局導(dǎo)航守衛(wèi)(鉤子)
// 驗(yàn)證一些用戶是否登錄
router.beforeEach((to, from, next) => {
console.log('before each invoked')
next()
// if (to.fullPath === '/app') {
// next({ path: '/login' })
// console.log('to.fullPath :'+to.fullPath )
// } else {
// next()
// }
})
router.beforeResolve((to, from, next) => {
console.log('before resolve invoked')
next()
})
// 每次跳轉(zhuǎn)后觸發(fā)
router.afterEach((to, from) => {
console.log('after each invoked')
})
new Vue({
router,
render: (h) => h(App)
}).$mount("#root")
路由獨(dú)享的守衛(wèi)
可以在路由配置上直接定義 beforeEnter 守衛(wèi):
export default [
{
path:'/',
redirect:'/app' //默認(rèn)跳轉(zhuǎn)路由
},
{
path: '/app',
// 路由獨(dú)享的守衛(wèi)鉤子
beforeEnter(to, from, next) {
console.log('app route before enter')
next()
}
component: Todo,
}
]
組件內(nèi)的守衛(wèi)
export default {
//進(jìn)來之前
beforeRouteEnter(to, from, next) {
// 不!能!獲取組件實(shí)例 `this`
// 因?yàn)楫?dāng)守衛(wèi)執(zhí)行前,組件實(shí)例還沒被創(chuàng)建
console.log("todo before enter", this); //todo before enter undefined
//可以通過傳一個(gè)回調(diào)給 next來訪問組件實(shí)例。在導(dǎo)航被確認(rèn)的時(shí)候執(zhí)行回調(diào),并且把組件實(shí)例作為回調(diào)方法的參數(shù)。
next(vm => {
// 通過 `vm` 訪問組件實(shí)例
console.log("after enter vm.id is ", vm.id);
});
},
//更新的時(shí)候
beforeRouteUpdate(to, from, next) {
console.log("todo update enter");
next();
},
// 路由離開
beforeRouteLeave(to, from, next) {
console.log("todo leave enter");
const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
if (answer) {
next()
} else {
//以通過 next(false) 來取消。
next(false)
}
},
props:['id'],
components: {
Item,
Tabs
},
mounted() {
console.log(this.id)
},
};
路由懶加載
參考:路由懶加載
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
用v-html解決Vue.js渲染中html標(biāo)簽不被解析的問題
這篇文章主要給大家介紹了如何利用v-html解決Vue.js渲染過程中html標(biāo)簽不能被解析,html標(biāo)簽顯示為字符串的問題,文中通過圖文介紹的很詳細(xì),有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-12-12
vue如何自動(dòng)化打包測(cè)試環(huán)境和正式環(huán)境的dist/test文件
這篇文章主要介紹了vue如何自動(dòng)化打包測(cè)試環(huán)境和正式環(huán)境的dist/test文件,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-06-06
Vue+Element實(shí)現(xiàn)頁(yè)面生成快照截圖
這篇文章主要為大家詳細(xì)介紹了Vue如何結(jié)合Element實(shí)現(xiàn)頁(yè)面生成快照截圖功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03
通過vue-cli3構(gòu)建一個(gè)SSR應(yīng)用程序的方法
這篇文章主要介紹了通過vue-cli3構(gòu)建一個(gè)SSR應(yīng)用程序,以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。2018-09-09
淺談Vue使用Cascader級(jí)聯(lián)選擇器數(shù)據(jù)回顯中的坑
這篇文章主要介紹了淺談Vue使用Cascader級(jí)聯(lián)選擇器數(shù)據(jù)回顯中的坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-10-10
vue-cli3 項(xiàng)目?jī)?yōu)化之通過 node 自動(dòng)生成組件模板 generate View、Component
這篇文章主要介紹了vue-cli3 項(xiàng)目?jī)?yōu)化之通過 node 自動(dòng)生成組件模板 generate View、Component的相關(guān)知識(shí),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04
vue elementUI select下拉框如何設(shè)置默認(rèn)值
這篇文章主要介紹了vue elementUI select下拉框如何設(shè)置默認(rèn)值問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10
vue中uni-app 實(shí)現(xiàn)小程序登錄注冊(cè)功能
這篇文章主要介紹了uni-app 實(shí)現(xiàn)小程序登錄注冊(cè)功能,文中給大家介紹了實(shí)現(xiàn)思路,以及vuex和本地緩存的區(qū)別,需要的朋友可以參考下2019-10-10
Vue移動(dòng)端實(shí)現(xiàn)調(diào)用相機(jī)掃描二維碼或條形碼的全過程
最近在使用vue開發(fā)的h5移動(dòng)端想要實(shí)現(xiàn)一個(gè)調(diào)用攝像頭掃描二維碼的功能,所以下面這篇文章主要給大家介紹了關(guān)于Vue移動(dòng)端實(shí)現(xiàn)調(diào)用相機(jī)掃描二維碼或條形碼的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08

