在组件安装之前,我想显示一个yuche/vue-strap
微调器,因为我必须通过AJAX请求加载数据。然后我希望微调器在请求完成后隐藏。微调器位于days.vue
模板之前的父cycles.vue
模板中。
以下是days.vue
:
<template>
<accordion :one-at-atime="true" type="info">
<panel :is-open="index === 0" type="primary" :header="'Day ' + day.day" v-for="(day, index) in days" :key="day.id">
<accordion :one-at-atime="true" type="success">
<panel is-open type="success" header="Cycles">
<spinner :ref="'cycles_spinner_' + day.id" size="xl" text="Loading cycles..."></spinner>
<cycles
:day="day"
>
</cycles>
</panel>
</accordion>
</panel>
</accordion>
</template>
<script>
export default {
props: [
'plan'
],
data() {
return {
days: {}
}
},
beforeMount: function () {
var self = this;
axios.get('/plans/' + this.plan.id + '/days/data')
.then(function (response) {
self.days = response.data;
})
.catch(function (error) {
console.log(error);
});
}
}
</script>
以下是cycles.vue
:
<template>
<accordion :one-at-atime="true" type="info">
<panel :is-open="index === 0" type="primary" :header="'Week ' + cycle.week + ': ' + cycle.name" v-for="(cycle, index) in cycles" :key="cycle.id">
<form v-on:submit.prevent="update">
....misc input fields here...
</form>
</panel>
</accordion>
</template>
<script>
export default {
props: [
'day'
],
data() {
return {
cycles: []
}
},
beforeMount: function () {
var self = this;
this.$parent.$refs['cycles_spinner_' + this.day.id].show();
axios.get('/plans/days/' + this.day.id + '/cycles/data')
.then(function (response) {
self.cycles = response.data;
this.$parent.$refs['cycles_spinner_' + this.day.id].hide();
})
.catch(function (error) {
console.log(error);
});
}
}
</script>
当我尝试this.$parent.$refs['cycles_spinner_' + this.day.id].show();
时,我收到错误Cannot read property 'show' of undefined
。
我也试过了this.$refs['cycles_spinner_' + this.day.id].show();
,但也犯了同样的错误。
我在这里做错了什么?是否有比我正在做的更清洁的方法?
答案 0 :(得分:0)
ref
s inside v-for
s生成数组。从文档(强调我的):
当
ref
与v-for
一起使用时,您获得的参考将是数组,其中包含镜像数据源的子组件。
所以而不是:
this.$parent.$refs['cycles_spinner_' + this.day.id].show();
你应该这样做:
this.$parent.$refs['cycles_spinner_' + this.day.id][0].show();
索引为0
,因为每次迭代只创建一个名为'cycles_spinner_' + this.day.id
的引用。
this
)在您的axios .then()
内,您将面临同样的问题。此外,在.then(function (response) {
内部不使用this
,请使用self
:
axios.get('/plans/days/' + this.day.id + '/cycles/data')
.then(function(response) {
self.cycles = response.data;
self.$parent.$refs['cycles_spinner_' + this.day.id][0].hide();
// ^^^^---------------- changed ----------------------^^^
})
.catch(function(error) {
console.log(error);
});