在使用vue-ant開發時使用collaps組件比較頻繁,自己封裝成組件,需要注意的是正常的封裝后容易出現兩個問題,分別是組件加載和點擊改變activeIndex的報錯:
下面是說明和解決:
1:初始化時容易報錯:
"TypeError: handler.call is not a function"問題
造成報錯原因就是生命周期鈎子函數mounted: {}是否有聲明了未定義方法或是只聲名了鈎子函數。
處理方法:1.把mounted: {}刪除掉,
2.把mounted: {}改為mounted(){},
2:點擊切換tab或顯示隱藏改變indexKey時報錯:
[Vue warn]: Property or method "currentIndex" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
原因是父組件點擊子組件傳遞項目中遇到父組件傳值 activeIndex=》子組件接收該值
由於父組件updated()方法中更改了this.activeIndex值,update方法除了父組件觸發這個方法,子組件也會觸發,即子組件會更改activeIndex的值,但是由於父子組件的傳遞機制,會造成報錯Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders....
因此在子組件使用該值時需要經過新變量(currentIndex)重新傳遞,這樣當這個值變更時,不會造activeIndex的更改
解決前代碼
父組件: <collaps :activeKey="activekey"></collaps> import collaps from '../../components/collapbox/index.vue' components:{collaps} data(){ return { activekey:['2'] } }, 子組件: <a-collapse v-model="activeKey"> props:[ "activeKey" ], watch: { activeKey(key) { console.log(key); }, },
解決后代碼對比:
父組件不變 子組件: <a-collapse v-model="activeKey"> props:[ "activeKey" ],//不變 data(){ return { //添加映射props的新data currentIndex:this.activeKey } }, watch://不變
這樣就可以正常點擊切換折疊和打開collapse,如果類似功能的組件自己封裝注意點相似