vue/eslint_vue/no-side-effects-in-computed-properties报错

发布时间 2023-11-11 01:01:39作者: Steperouge
  • 出现这个错误的缘由是因为我在vue3中的computed中, 把computed的回调函数当做数据监听器处理程序, 在里面修改了ref定义的变量数据的值.
const curArticle = computed(() => {
  if (curArticleList.value.length === 0) {
    articleData.value.name = articleData.value.content = ''
    return null
  } else {
    articleData.value.name = newVal.name
    articleData.value.content = newVal.content
    return curArticleList.value[articleIdx.value]
  }
})
  • 部分博客建议将修改数据的逻辑包装成一个函数然后在computed中调用可以规避这一问题, 但是我想computed应该设计初衷应该只是用于数据的动态依赖更新, 而不是用于数据的监听; 因此我选择了将逻辑函数重新整合到watch中
const curArticle = computed(() => {
  if (curArticleList.value.length === 0) {
    return null
  } else {
    return curArticleList.value[articleIdx.value]
  }
})

watch(curArticle, newVal => {
  if (newVal === null) {
    articleData.value.name = articleData.value.content = ''
  } else {
    articleData.value.name = newVal.name
    articleData.value.content = newVal.content
  }
})