重构带有不一致道具的value组件



我想重构Vue组件,其中相同的数据以不同的结构出现。

例子约会。vue组件:

<template>
<div>
<div v-if="config.data.user.user_id">
{{ config.data.user.user_id }}
</div>
<div v-if="config.data.user.address.full_address">
{{ config.data.user.address.full_address }}
</div>
.
.
.
</div>
</template>
<script>
export default {
name: 'appointment',
props: {
config: {
required: true,
},
},
// Some operations uses 'config' prop
//.
//.
//.
}
</script>

在CreateAppointment。使用appointment .vue的组件:

<template>
<div>
<appointment :config="data"/>
.
.
.
</div>
</template>
<script>
export default {
name: 'Create Appointment',
data() {
return {
data: null,
};
},
methods: {
openAppointment() {
const result = // api get operation that returns object which I'll use on Appointment.vue
if (result) {
const temp = {
user: null,
}
temp.appointment_id = result.appointment_id;
.
.
.
temp.user.user_id = result.user_profile.user_id;
.
.
.
this.data = { ...temp };
}
}
}
}
</script>

在AppointmentList。vue使用Appointment.vue:

<template>
<div>
<appointment :config="data"/>
.
.
.
</div>
</template>
<script>
export default {
name: 'AppointmentList',
data() {
return {
data: null,
};
},
methods: {
openAppointment() {
const result = // api get operation that returns object which I'll use on Appointment.vue
if (result) {
const temp = {
user: null,
}
temp.appointment_id = result.appointment_id;
.
.
.
temp.user.user_id = result.user_id;
temp.user.name = result.user_name;
.
.
.
this.data = { ...temp };
}
}
}
}
</script>

可以看到,在CreateAppointment中。vue Api返回user_profile对象中的user_id。但在ListAppointment中。值,Api以另一种结构返回数据。在这种情况下,无论约会。我需要将传入的数据转换为Appointment形状。vue想要的。我该如何避免这种情况呢?(我不可能更改从API返回的数据。)我想使用mixin或Wrapper组件。在这种和类似的情况下,实现什么样的解决方案是有意义的?

如果你不能改变API响应方案,唯一的方法是根据你的需要改变数据:(如果您必须在多个地方对user进行相同的操作,我建议添加辅助函数或mixin,否则就保留原样并在必要时提取逻辑。顺便说一下,为什么你必须多次获取相同的数据,或者它不一样?你可以从子组件向父组件发出事件,并从那里处理API调用。这样,您将始终拥有一致的数据…

最新更新