Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
程序員Web前端干貨詳解Vue-Router路由與配置,現在的很多應用都流行SPA應用(singe page application) 。傳統的項目大多使用多頁面結構,需要切換內容的時候我們往往會進行單個html文件的跳轉,這個時候因受到網絡、性能的影響,瀏覽器會出現不定時間的空白界面,用戶體驗不好。而單頁應用則是用戶通過某些操作更改地址欄url之后,動態的進行不同模板內容的無刷新切換,用戶體驗好。而在vue2.0版本后,vue官方推出vue-router插件來實現單頁面的路由跳轉,內部原理就是通過組件之間的切換(組件的卸載與安裝)去實現整個頁面無刷新的效果。
一.項目引入路由并配置:
1.在vue項目中,通過cnpm或者yarn的方式進行vue-router的安裝
cnpm i vue-router -S
yarn add vue-router -S
2.接下來需要在入口文件main.js里面進行路由的引入與注冊
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
3. 創建router路由器
new Router({
routes:[
{path:"",component:}
]
})
4. 創建路由表并配置在路由器中
var routes=[
//path為路徑,component為路徑對應的路由組件
{path,component}
]
new Router({
routes
})
5. 在根實例里注入router,目的是為了讓所有的組件里都能通過this.$router、this.$route來使用路由的相關功能api
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
6. 利用router-view來指定路由切換的位置
7. 使用router-link來創建切換的工具,會渲染成a標簽,添加to屬性來設置要更改的path信息,且會根據當前路由的變化為a標簽添加對應的router-link-active/router-link-exact-active(完全匹配成功)類名
<router-link to="main">main</router-link>
<router-link to="news">news</router-link>
.router-link-active{
color:red;
}
項目中多級路由配置:
在創建路由表的時候,可以為每一個路由對象創建children屬性,值為數組,在這個里面又可以配置一些路由對象來使用多級路由,注意:只在一級路由的path前加 '/ '
const routes=[
{path:'/home,component:Home},
{path:'/list',component:List,children:[
{path:'inner',component:Inner},
{path:'outer',component:Outer}
]},
]
二級路由組件的切換位置依然由router-view來指定(指定在父級路由組件的模板中)
<router-link to='/home/inner'>inner</router-link>
<router-link to='/home/outer'>outer</router-link>
<router-view></router-view>
但是這樣發現當路由路徑多級的時候,不利于快速定位路由匹配的組件。所以,可以通過命名路由的方式去實現以上代碼。
我們可以給路由對象配置name屬性,當我們在跳轉的時候直接寫name:inner就會快速的找到此name屬性所對應的路由,不需要寫大量的urlpath路徑了。如下所示:
{path:'inner',component:Inner,name:'inner'}
這樣的話,我們就可以方便的根據路由的不同進行組件之間的映射。但是,做大型項目開發的時候,我們也會發現很多的路由寫在routes這個里面,會讓router這個文件變得很大不利于維護管理。除此之外,如果通過這樣的方式還會導致當用戶打開首頁的話,因為webpack打包的時候,加載內容異常的多導致打開速度很慢。所以我們需要對我們的路由采取懶加載的方式進行引入:
const routes=[
homeRouter
]
//homeRouter.js文件里面
export defult {
Name:’homeRouter’,
Path:’/home’
component:()=> import('./my-async-component')}
}
Vue-Router的路由守衛:
在項目開發中,我們經常會在路由跳轉前后做一些操作。例如我們可以通過利用vue-router里面提供的路由守衛結合axios攔截器實現項目的登錄攔截等操作。Vue-router里面提供的路由守衛可以分為三大類,分別是全局路由守衛、單個的路由鉤子的路由守衛、路由組件內部的路由守衛。好,我們依次來看:
通過 router.beforeEach 或者router.afterEach注冊一個全局守衛:
1-1
router.beforeEach((to, from, next)=> {
//會在任意路由跳轉前執行,next一定要記著執行,不然路由不能跳轉了
next()
})
守衛方法需要接受三個參數:to、from、next
to:即將要進入的目標對象
From:當前導航正要離開的路由
Next: 一定要調用該方法來 resolve 這個鉤子。執行效果依賴 next 方法的調用參數。
1-2
//會在任意路由跳轉后執行
Router.afterEach((to,from)=>{
})
單個路由鉤子守衛:
只有beforeEnter,在進入前執行,to參數就是當前路由
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next)=> {
// next也是必須要寫的
}
}
]
路由組件鉤子守衛:
beforeRouteEnter (to, from, next) {
//內部不能調用this 當這個路由調用時,組件沒有被初始化
},
beforeRouteUpdate (to, from, next) {
// 內部可以訪問組件實例 `this`
//路由內部動態參數改變了,組件被復用的時候調用(/list/1跳入/list/2,詳情組件復用的時候)
},
beforeRouteLeave (to, from, next) {
// 可以訪問組件實例 `this` 路由離開這個組件的時候進入
}
以上就是Vue-Router里面的核心技術點,需要在項目中不斷的練習、具體到業務邏輯中使用才能更好的理解、滲透,其次多加記憶、鞏固才可更加清晰。
是Vue官方插件https://router.vuejs.org/zh/guide/#html。
用 Vue.js + Vue Router 創建單頁應用,是非常簡單的。使用 Vue.js ,我們已經可以通過組合組件來組成應用程序,當你要把 Vue Router 添加進來,我們需要做的是,將組件 (components) 映射到路由 (routes),然后告訴 Vue Router 在哪里渲染它們。
簡單舉例子:
聲明式路由:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> </head> <body> <div id="app"> <h1>Hello App!</h1> <p> <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> </p> <router-view></router-view> </div> <script type="text/javascript"> const Foo=Vue.extend({ template: '<div>foo</div>' }) const Home=Vue.extend({ template:'<div>沒有點擊link時,默認的頁面</div>'}) const Bar={ template: '<div @click="luyou">bar</div>', methods: { luyou() { console.log(this.$route) } } } const routeses=[{path:'',component:Home}, { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ] const router11=new VueRouter({ routes: routeses }) const app=new Vue({ el: '#app', router: router11, mounted() { // this.$router.push('/') console.log(this.$router) console.log(this.$route) } }) </script> </body> </html>
編程式路由:
怎么把聲明式改為編程式:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>編程式導航</title> <script src="https://cdn.bootcss.com/vue/2.6.9/vue.js"></script> <script src="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.js"></script> <style> button, .router-link{ padding: 10px 15px; border: none; outline: none; font-size: 20px; color: #fff; background: linear-gradient(to right, blue, red, green); background-color: #000; } </style> </head> <body> <div id="app"> <!--最初的 router-link 模式--> <router-link class="router-link" to="/path/RouterLink">原始路由</router-link> <!--使用 router.push 方法--> <button type="button" @click="routerPush">router.push 方法</button> <!--使用 router.replace 方法--> <button type="button" @click="routerReplace">router.replace 方法</button> <!--使用 router.go 方法--> <button type="button" @click="routerGo">router.go 方法</button> <router-view></router-view> </div> <script> // 創建一個路由組件 用于輸出內容 const view={ template: "<div>" + "<h1>我點擊的是 {{$route.params.msg}}</h1>" + "</div>" }; // 定義路由 const routes=[{ path: '/path/:msg', component: view }]; // 創建路由實例 const router=new VueRouter({ routes }); const app=new Vue({ router, methods: { // 使用 router.push 替換 <router-link to="xxx"></router-link> // 可點擊瀏覽器后退按鈕后退至上一步 routerPush() { this.$router.push({ path: "/path/routerPush" }) }, // 使用 router.replace 替換 <router-link to="xxx"></router-link> // 不可后退 routerReplace() { this.$router.replace({ path: "/path/routerReplace" }) }, // router.go(n),接收一個整數,如果為正數則 前進 n 步,負則后退 n 步 routerGo() { this.$router.go(-1) } } }).$mount("#app"); </script> </body> </html>
這兩個簡單的案例搞懂了,也就懂了一點基礎了。
端路由與前端路由
后端路由:應用程序如何去處理不同的url地址發送過來的請求。
前端路由:不同的url地址要渲染不同的頁面效果出來。
后端路由與前端路由最本質的一個區別:前端路由只處理 GET 請求。
vueRouter
Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,讓構建單頁面應用變得易如反掌。包含的功能有:
嵌套的路由/視圖表
模塊化的、基于組件的路由配置
路由參數、查詢、通配符
基于 Vue.js 過渡系統的視圖過渡效果
細粒度的導航控制
帶有自動激活的 CSS class 的鏈接
HTML5 歷史模式或 hash 模式,在 IE9 中自動降級
自定義的滾動條行為
使用vueRouter
在 Vue 核心之后引入 VueRouter
準備路由頁面組件(跟路由相關的組件,就叫做路由頁面組件)
components: {
home: {
template: `<h1>home</h1>`,
}
...多個
}
const routes=[
// 一個對象就是一條路由規則
{
// 每一條規則有一些配置項,主要的是 path 和 component
// path - 路由url地址,一般是#號后面的部分
// component 使用哪個路由頁面組件去渲染,
// 不能是組件名字的字符串
// 可以直接提供一個包含組件配置項的對象即可
// name 推薦任何組件都設置一個 name 的選項這個選項就是給組件取個名字
path: "/home",
name: "home",
component: home,
}
...多個
]
new Vue({
// 配置一個 router 選項
router,
});
<div id="app">
<router-view></router-view>
</div>
路由模式
Vue 中 路由有兩種不同的模式
hash 模式 (默認模式)
使用 URL 的 hash 來模擬一個完整的 URL,于是當 URL 改變時,頁面不會重新加載。
hisotry 模式
history模式是基于最新的HTML5里面history相關的api進行的一些操作。不過這種模式要玩好,還需要后臺配置支持不然會出現404找不到頁面這種問題。history模式時,重定向會有些問題,需要頁面的名字叫index.html才行。history模式只能兼容到IE10及以上。
在 new VueRouter() 的時候,配置 mode 選項就可以切換模式
const router=new VueRouter({
// 路由模式,只能從 hash 與 history 中選擇一個
mode: "history",
routes
});
聲明式導航 (用 router-link 來控制路由跳轉)
與 router-view 一樣,都是引入了 vue-router 之后,提供的全局組件
router-link 的作用就是實現路由的跳轉(url的跳轉)它本質上就是一個a標簽。我們推薦使用它,而不是去用a標簽來跳轉。
語法:
<router-link to="/home">home</router-link>
to 屬性是必須的用來設置點擊時跳轉到哪里
使用 router-link 就不需要去寫 # 號了,它會根據當前路由的模式來決定最終渲染出去的a標簽的href屬性有沒有 # 號。
默認情況下當前的路由地址與某個router-link的to屬性匹配時,會給渲染出去的a元素添加上兩個 class ,可以使用這兩個中的任意一個操作css 樣式,這能夠更方便的去實現高亮效果。
router-link-exact-active
router-link-active
也可以設置 router-link 組件的 active-class 屬性,屬性值為某個class名字
希望默認的 router-link-active=> active
active-class=“active”
希望默認的 router-link-exact-active=> exact-active
exact-active-class=“exact-active”
編程式導航 (用js控制路由跳轉)
$router
使用 vue-router 之后,在 vue 的原型上提供了一個 $router 對象, 使用這個對象的一些方法來進行路由的跳轉。
this.$router.push()
就相當于普通的 router-link 它的參數可以是:
字符串,要跳轉到路由的path
對象,對象中配置 path 屬性。
this.$router.replace()
就相當于帶有 replace 屬性 的 router-link 它的參數可以是:
1. 字符串,要跳轉到路由的path
2. 對象,對象中配置 path 屬性。
其余的一些方法
this.$router.back()=> 后退 history.back()
this.$router.go(num)=> 前進或后退,根據傳遞參數是正數還是負數來決定 history.go()
this.$router.forward()=> 前進 history.forward()
push() 與 replace() 和 router-link 上的 to 屬性,傳遞為對象時,對象有哪些屬性:
path
路由重定向
name
路由別名
query
query 參數
params
params 參數
params 與 path 會產生沖突,請使用 name 和 params 結合使用
meta
路由元信息
*請認真填寫需求信息,我們會在24小時內與您取得聯系。