用空間換時間優化去除陣列中重複字元
阿新 • • 發佈:2020-12-16
技術標籤:VueJS
文章目錄
vue-router
動態路由匹配
我們經常需要把某種模式匹配到的所有路由,全都對映到同個元件。例如,我們有一個 User 元件,對於所有 ID 各不相同的使用者,都要使用這個元件來渲染。那麼,我們可以在 vue-router 的路由路徑中使用“動態路徑引數”(dynamic segment) 來達到這個效果:
const User = { template: '<div>User</div>' } const router = new VueRouter({ routes: [ // 動態路徑引數 以冒號開頭 { path: '/user/:id', component: User } ] })
一個“路徑引數”使用冒號 : 標記。當匹配到一個路由時,引數值會被設定到 this.$route.params,可以在每個元件內使用。於是,我們可以更新 User 的模板,輸出當前使用者的 ID:
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
響應路由引數的變化
提醒一下,當使用路由引數時,例如從 /user/foo 導航到 /user/bar,原來的元件例項會被複用。因為兩個路由都渲染同個元件,比起銷燬再建立,複用則顯得更加高效。不過,這也意味著元件的生命週期鉤子不會再被呼叫。
複用元件時,想對路由引數的變化作出響應的話,你可以簡單地 watch (監測變化) $route 物件:
const User = {
template: '...',
watch: {
$route(to, from) {
// 對路由變化作出響應...
}
}
}
路由懶載入
為給客戶更好的客戶體驗,元件載入速度更快一些,解決白屏問題。
使用ES的import
component: () => import( "../views/application/application")
關於this.$router.push、replace、go的用法和區別
- this.$router.push
跳轉到指定url路徑,並想history棧中新增一個記錄,點選後退會返回到上一個頁面
// 字串
this.$router.push('index')
// 物件
this.$router.push({path: 'login-pw'})
// 帶引數
this.$router.push({path: 'login-pw', query: {'account': this.account.account}})
// 跳轉後的頁面獲取引數
this.account.account = this.$route.query.account
-
this.$router.replace
跳轉到指定url路徑,但是history棧中不會有記錄,點選返回會跳轉到上上個頁面 -
this.$router.go(n)
向前或者向後跳轉n個頁面,n可為正整數或負整數