子组件没有事件,如何向父组件传值?
大家会提出疑问!
1. 子组件没有事件为什么会发生数据变更?
2.没发生数据变更为什么要传递数据给父组件呢?
3.如果子组件只是展示数据,数据放在父组件通过props传递给子组件就好了,何必这么搞!
那么如果出现了这样的问题,如何解决呢?
答案是:使用 ref !!
思路如下:
父组件调用子组件的地方使用ref定义,子组件写一个方法getChildMethod,在父组件中通过this.$refs.getChildMethod();
就完成了父组件接受值!
具体看看展示图和代码吧!
父组件代码块
<template>
<div class="fingerprint-bottom">
<el-tabs v-model="activeName">
<div class="fingerprint-bottom">
<el-tabs v-model="activeName">
<el-tab-pane v-for="(item,index) in optionS" :key="index" :label="item.label" :name="item.name">
<!-- 子组件 -->
<EditAssetTab :ref="item.type" type="item.type" :edit-asset-data="editAssetData" :active-name="item.name" />
</el-tab-pane>
</el-tabs>
</div>
</el-tabs>
<el-button type="primary" size="small" @click="submitAsset">提交</el-button>
</div>
</template>
<script>
import EditAssetTab from './editAssetTab.vue';
export default {
data() {
return {
// 举例子代码不是很严谨 仅仅参考
optionS: [
{
label: '设备信息',
name: 'first',
type: 'a'
}, {
label: '设备信息',
name: 'first',
type: 'a'
}, {
label: '设备信息',
name: 'first',
type: 'a'
}, {
label: '设备信息',
name: 'first',
type: 'a'
}, {
label: '设备信息',
name: 'first',
type: 'a'
}, {
label: '设备信息',
name: 'first',
type: 'a'
}
],
}
methods:{
// 提交按钮
submitAsset() {
// 调用子组件的获取数据方法
const refsMap = ['a', 'b', 'c', 'd', 'e', 'f'];
refsMap.map(item => {
this.originData = { ...this.originData, ...this.$refs[item].getAllQuery() };
});
}
}
}
子组件代码块
// 获取所有数据
getAllQuery() {
if (this.type === 'a') {
return {
// 网络信息部分
ip_type: this.ip_type, // IP类型
ip_nat: this.ip_nat, // 映射IP
.......
};
} else if (this.type === 'b') {.......}//依次类推