描述: 編程式路由跳轉到當前路由(參數不變), 會拋出NavigationDuplicated的警告錯誤
聲明式路由跳轉內部已經處理
原因:vue-router3.1.0之后, 引入了push()的promise的語法
如果沒有通過參數指定成功或者失敗回調函數就返回一個promise來指定成功/失敗的回調
且內部會判斷如果要跳轉的路徑和參數都沒有變化, 會拋出一個失敗的promise
解決: 1:在跳轉時指定成功或失敗的回調函數, 或者catch處理錯誤
2: 修正Vue原型上的push和replace方法 (優秀)
header.vue
html部分
<div class="searchArea"> <form action="###" class="searchForm"> <input type="text" id="autocomplete" class="input-error input-xxlarge" v-model="keyword"/> <button class="sui-btn btn-xlarge btn-danger" type="button" @click="toSearch">搜索</button> </form> </div>
js部分
data(){
return {
keyword:''
}
},
methods:{
toSearch(){
//字符竄寫法,用的不多
// this.$router.push(`/search/${this.keyword}?keyword=${this.keyword.toUpperCase()}`)
// 如果使用對象:
// 傳遞params參數必須和name配合
// path和params無法配合使用
// path和query是可以使用的
// name和query也是可以的
// 以后盡量寫name
this.$router.push({
// path:'/search',
name:'search',
query:{
keyword1:this.keyword.toUpperCase()
},
params:{
//如果傳遞params參數是一個空串,那么路徑會有問題,傳過去如果是undefined就沒事
keyword:this.keyword || undefined
}
}) //.catch(()=>{})用來處理多次push點擊報錯問題,但是不能一勞永逸
}
方法一:直接在后面加.catch(()=>{}), 因為push()返回的是一個promise
方法二,直接在VueRouter的原型中添加方法,解決
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
//終極解決多次觸發push或者repalce,報錯的問題
//NavigationDuplicated
const originPush = VueRouter.prototype.push
const originReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function(location,onResolved,onRejected){
if(onResolved === undefined && onRejected === undefined){
// originPush.call目的是讓VueRouter實例化對象去調用
//如果不加,那就是window在調用
return originPush.call(this,location).catch(() => {})
}else{
return originPush.call(this,location,onResolved,onRejected)
}
}
VueRouter.prototype.replace = function(location,onResolved,onRejected){
if(onResolved === undefined && onRejected === undefined){
// originPush.call目的是讓VueRouter實例化對象去調用
//如果不加,那就是window在調用
return originReplace.call(this,location).catch(() => {})
}else{
return originReplace.call(this,location,onResolved,onRejected)
}
}
import routes from '@/router/routes'
export default new VueRouter({
routes
})
原因:vue-router3.1.0之后, 引入了push()的promise的語法
如果沒有通過參數指定成功或者失敗回調函數就返回一個promise來指定成功/失敗的回調
且內部會判斷如果要跳轉的路徑和參數都沒有變化, 會拋出一個失敗的promise
二定義home內部的組件
在home內部定義這些非路由組件 brand,floor, like, listcontainer,rank,recommend,typenav, 注意要拷貝圖片過來
其中typenav,商品分類導航組件,search組件也要用到,將typenav弄到components中去復用, 在main.js中全局注冊
// 引入公共組件typenav
import TypeNav from '@/components/TypeNav'
Vue.component('TypeNav', TypeNav)