父组件调用子组件方法,一直报 not a function,看了好多文章,不仅都没能解决我的问题,甚至还有些误导我。
ps:父组件中的子组件必须要写ref、components
1、父组件not a function
这种情况下,一般都是未找到子组件的ref。如上图所示,我的子组件放在v-for中,这时我的ref是个数组,就不能直接用this.$refs.inputOne.formInput()。需要拿到 ref 的下标才行
formInput() {
this.$nextTick(() => {
this.inputList.forEach((item, index) => {
this.$refs.inputOne[index].formInput();
});
});
},
2、undefined
这种情况下,一般都是父组件调用子组件方法的时候,子组件还未渲染成功。可以在使用父组件调用子组件方法的时候,使用this.$nextTick()
formInput() {
this.$nextTick(() => {
this.$refs.inputOne.formInput();
});
},