1. 程式人生 > 實用技巧 >元件化開發過程使用vue-ant框架父元件傳值動態改變activeIndex容易出現的問題

元件化開發過程使用vue-ant框架父元件傳值動態改變activeIndex容易出現的問題

在使用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,如果類似功能的元件自己封裝注意點相似