在使用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,如果类似功能的组件自己封装注意点相似