在挂载组件之前,我想显示一个yuche/vue-strap微调器,因为我必须通过AJAX请求加载数据。然后,我希望微调控件在请求完成后隐藏。微调器位于cycles.vue模板之前的父days.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();,但给出了相同的错误。
我在这里做错了什么?有没有比我现在做的更干净的方法?
发布于 2018-03-24 11:48:20
refs inside v-fors生成数组。来自文档(重点是我的):
当
ref与v-for一起使用时,您得到的ref将是一个包含镜像数据源的子组件的数组。
因此,不是:
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的引用。
在axios promises内部,同样的问题(注意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);
});https://stackoverflow.com/questions/49460436
复制相似问题