问题
I am creating a DOB Form.
I am using VueJS in the form. The user should their date of month first so that day is displayed according to the number of days in the respective month.
I am using filter()
and the problem is this
inside filter()
is undefined. How can I fix this?
new Vue ({
el: '.app',
data: {
months: [
{month: 'January', days: 31},
{month: 'February', days: 28},
{month: 'March', days: 31},
{month: 'April', days: 30},
{month: 'May', days: 31},
{month: 'June', days: 30},
{month: 'July', days: 31},
{month: 'August', days: 31},
{month: 'September', days: 30},
{month: 'October', days: 31},
{month: 'November', days: 30},
{month: 'December', days: 31},
],
selectedMonth: []
},
computed: {
filterDays() {
return this.months.filter(function(value) {
return value.month === this.selectedMonth;
});
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div class="app">
<select id="dobd">
<option v-for="day in filterDays[0].days" :value="day">{{ day }}</option>
</select>
</div>
I know using a global variable might be the solution but I want to use selectedMonth
inside data()
due to my own needs.
回答1:
With function () {}
the context (this
) is lost. Which means, inside the filter
argument function, this
will not be the Vue instance.
There are some possible solutions:
Use arrow functions (preferred):
filterDays() { return this.months.filter((value) => { return value.month === this.selectedMonth; }); }
Use
.bind()
:filterDays() { return this.months.filter(function(value) { return value.month === this.selectedMonth; }.bind(this)); }
Use a local variable outside the function:
filterDays() { let vm = this; return this.months.filter(function(value) { return value.month === vm.selectedMonth; }); }
Demo:
new Vue ({
el: '.app',
data: {
months: [
{month: 'January', days: 31},
{month: 'February', days: 28},
{month: 'March', days: 31},
{month: 'April', days: 30},
{month: 'May', days: 31},
{month: 'June', days: 30},
{month: 'July', days: 31},
{month: 'August', days: 31},
{month: 'September', days: 30},
{month: 'October', days: 31},
{month: 'November', days: 30},
{month: 'December', days: 31},
],
selectedMonth: 'January' // changed to a valid month
},
computed: {
filterDays() {
return this.months.filter((value) => {
return value.month === this.selectedMonth;
});
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div class="app">
<select id="dobd">
<option v-for="day in filterDays[0].days" :value="day">{{ day }}</option>
</select>
</div>
来源:https://stackoverflow.com/questions/49714015/why-does-this-inside-filter-gets-undefined-in-vuejs