这个代码为什么会出现[Vue warn]: Maximum recursive updates exceeded in component <Grammar>. This means you have a reactive effect that is mutating its own dependencies and thus recursively triggering itself. Possible sources include component template, render function, updated hook or watcher source function这个错误。
<template v-for="(item, index) in flattenSpans" :key="index">
<span class="sentence" :style="getBackgroundColor(item.w_span.label)">{{ item.text }}
</span>
</template>
function getBackgroundColor(label) {
let color
switch (label) {
case '陈述句/祈使句':
color = '#F9FBE8'
break
case '从句':
color = '#FFF3E1'
break
case '特殊疑问句':
color = '#FCE5ED'
break
case '倒装句':
color = '#F3E6F5'
break
case '一般疑问句':
color = '#FFECEF'
break
case '介词短语':
color = '#FFF8E2'
break
case '非谓语':
color = '#E2F5FE'
break
}
if (!oldLabel.value || oldLabel.value == label) {
oldLabel.value = label
return { backgroundColor: color }
} else if (oldLabel.value != label) {
oldLabel.value = label
return {
backgroundColor: color,
marginLeft: '4.8px'
}
}
}
原因: 这个错误可能是由于你的 getBackgroundColor
函数在逻辑中修改了响应式数据并触发了无限递归。在Vue.js中,一些触发更新的操作,如果不谨慎使用,可能导致无限递归更新。
解决:把let oldLabel = ref()改为let oldLabel