gpt4 book ai didi

javascript - Vue.js 组件中的 DRY 初始化

转载 作者:搜寻专家 更新时间:2023-10-30 22:51:52 24 4
gpt4 key购买 nike

当组件初始化时,我运行数据回调,如下所示:

data(){
return {
name: myNameGetter(),
age: myAgeGetter(),
// etc...
}
},

然后警告一些父组件关于这个组件的逻辑:

created(){
this.$emit('personFullName', this.getFullName());
},

然后我的观察者内部也有相同的逻辑:

watch: {
person: function(){
this.name = myNameGetter();
this.age = myAgeGetter();
this.$emit('personFullName', this.getFullName());
}
}

有没有办法干掉这个?

我想到的唯一想法是:

watch: {
person: function(){
const data = this.data();
for (let key in data) this[key] = data[key];
this.$emit('personFullName', this.getFullName());
}
}

但感觉还是有点不干。社区如何解决这个问题?

最佳答案

so that was a example, the real life app is a calendar. In the container I have the calendar header. Then I have child components for month, week and day view. The title in the container is set by the child component. So if its month view the child will $emit "march 2017", if its the day view the other child component will $emit "31st march". And so on. The problem is that I have to call that getter function in data when the component initialises, also on watch and emit that to parent when created. This is what I want to DRY.

我之前在 Vue 中制作了一个日期/时间选择器,它有点类似于您的日历组件,因为有一个容器组件 (DateTimePicker),它有 2 个子组件(DatePicker 和 TimePicker)。一次只有一个子组件可见,具体取决于是否正在编辑日期或时间。

我认为重构组件共享数据的方式会更好。在我看来,子组件与 Calendar 组件紧密耦合(这很好)。我不确定您的日历组件是用于用户输入(用户可以选择日期吗?),还是仅用于显示特定日期。

为什么由子组件负责确定标题?每个子组件共享相同的日期,因此日历组件可以根据可见的子组件轻松确定标题,例如:

<div class="calendar">
<div class="cal-title">{{ title }}</div>
<day v-if="view === 'day'" :value="date" @input="onInput"></day>
<week v-if="view === 'week'" :value="date" @input="onInput"></week>
<month v-if="view === 'month'" :value="date" @input="onInput"></month>
</div>
{
props: ['date'],

data() {
return {
view: 'day',
// This component has no internal state for the date
};
},

computed: {
title() {
switch (this.view) {
case 'day': return this.date.format('day'); break;
case 'week': return this.date.format('week'); break;
case 'month': return this.date.format('month'); break;
}
},
},

methods: {
onInput(date) {
this.$emit('input', date);
},
},
}

关于javascript - Vue.js 组件中的 DRY 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43134597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com