Vue以表格形式跟踪问题索引



我有一个组件'form',它包含6个问题。我有一个生成手机输入的插件。电话问题是第3个,我只需要在问题编号是第3时生成它。我在data()钩子中有一个问题索引,所以当索引为3时,我需要调用函数generateTel(),因为只有当索引为3。

html看起来像:

<div v-if="index === 1" class="question"></div>
<div v-if="index === 2" class="question"></div>
<div v-if="index === 3" class="question"></div>
<div v-if="index === 4" class="question"></div>
<div v-if="index === 5" class="question"></div>
<div v-if="index === 6" class="question"></div>

如何跟踪索引何时等于3?或者也许这不是最好的练习,我不应该使用v-if?

注:Bergur的解决方案有效,但我必须添加一些更正:

watch: {
index(newVal) {
if (newVal === 3) {
let ref = this // to avoid this.generateTel() is not a function error
setTimeout(function () { // add setTimeout to avoid calling method on undefined 
ref.generateTel()
}, 100)
}
}
}

使用手表:https://v2.vuejs.org/v2/guide/computed.html#Watchers

在您的组件中:

watch: {
index(newVal) {
if (newVal === 3) {
this.generateTel()
}
}
}

最新更新