从组件外部调用函数,但在v-for循环中呈现



我有一些组件,它在v-for循环中渲染了6次。我正在尝试执行onclick函数,该函数将调用指定图表组件内部的方法。但现在我犯了这样的错误$refs.chart1.pauseChart((不是一个函数。这就是我试图实现它的方式:

<BaseChart ref="`chart$[index]`" @click="pauseChart(index)"/>
pauseChart(index) {
this.$refs.[`chart${index}`].pauseChart()
}

v-for内部的ref是数组,而不是奇点。因此,如果你有

<template v-for="(something, index) in list">
<BaseChart ref="chart" :key="index" @click="pauseChart(index)" />
</template>

你应该使用

methods:
{
pauseChart(idx)
{
this.$refs.chart[idx].pauseChart();
}
}

有关更多信息,请参阅Vue文档

ref将具有一个数组。因此,您必须使用0索引来访问它。

实时演示

Vue.component('child', {
methods: {
pauseChart() {
console.log('child method call');
}
},
props: ['childmsg'],
template: '<p v-on="$listeners">{{ childmsg }}</p>',
});
var app = new Vue({
el: '#app',
methods: {
pauseChart(chartIndex) {
this.$refs[chartIndex][0].pauseChart();
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<div v-for="index in 6" :key="index">
<child childmsg="Hello Vue!" :ref="`chart${index}`" @click="pauseChart(`chart${index}`)">
</child>
</div>
</div>

最新更新