首先先写一下父组件调用静态子组件的方法
父组件
<template>
<div>
<childComp ref="childRef"></childComp>
</div>
</template>
<script>
import childComp from './child';
export default{
components: { childComp },
methods: {
getChildData(){
this.$refs.childRef.getData();
}
}
}
</script>
子组件
<template>
<div>子组件</div>
</template>
<script>
export default{
methods: {
getData(){
console.log('获取数据')
}
}
}
</script>
当在调用动态子组件时发现这种方法并不生效,于是就打印$ref的取值发现,读取到的是个数组
父组件调用动态子组件方法如下:
父组件
<template>
<div class="detail">
<el-tabs v-model="activeName" @tab-click="handleClick">
<el-tab-pane v-for="item in tabConfig" :key="item.label" :label="item.label" :name="item.name">
<component
:ref="item.name"
:is="item.name"
:detailInfo="detailInfo"
v-on="$listeners"
v-bind="$attrs"
@linkMore="linkMore"
></component>
</el-tab-pane>
</el-tabs>
</div>
</template>
<script>
import Application from './application';
import Version from './version';
import Merge from './merge';
export default {
components: { Application, Version, Merge },
data() {
return {
activeName: 'Application',
tabConfig: [
{
label: '应用',
name: 'Application'
},
{
label: '版本',
name: 'Version'
},
{
label: '合并',
name: 'Merge'
}
]
}
},
methods: {
handleClick(item) {
console.log(this.$refs[item.name])
if (this.$refs[item.name].length > 0) {
this.$refs[item.name][0].getApplicationInfoApi();
} else {
this.$refs[item.name].getApplicationInfoApi();
}
}
}
}
</script>
子组件
<script>
export default {
methods:{
async getApplicationInfoApi() {
try {
const params = {
appCode: this.detailInfo.appCode,
installCode: this.detailInfo.installCode || ''
};
const res = await this.$api.usageShopManage.getApplicationInfo(params);
const { androidPackage, iosPackage } = res.data;
this.androidPackage = androidPackage;
this.iosPackage = iosPackage;
} catch (e) {
console.log(e);
}
}
}
}
</script>