Vize

vize:croquis/cf/computed-side-effects

计算 getter 写入状态或执行其他副作用。

默认严重程度 自动修复 选项
不产生诊断 无;请检查相关文件并应用修复 无针对单个诊断代码的选项;受支持的 CLI 诊断可覆盖严重程度

适用范围: 已分析的组件图,以及下方说明的受支持事实

这是目前没有实现的公开诊断约定。下方错误与正确示例解释风险及修复;目前没有任何标志能使此诊断代码触发。

共享项目文件

错误和正确示例都使用这些不变的文件。在项目中安装导入的包:Vue,以及示例中出现的 vue-router 或 Pinia。遵循版本特定的支持说明。入口根文件显式展示组件关系。

main.ts

import { createApp } from 'vue';
import App from './App.vue';
createApp(App).mount('#app');

index.html

<!doctype html>
<html lang="en"><head><meta charset="UTF-8"><title>Contract scenario</title></head>
<body><div id="app"></div><script type="module" src="/main.ts"></script></body></html>

App.vue

<script setup lang="ts">
import { useDouble } from './use-double';
const { count, doubled, lastCalculated } = useDouble();
</script>

<template>
<button @click="count++">Increment {{ count }}</button><p>{{ doubled }} / {{ lastCalculated }}</p>
</template>

错误示例

求值 doubled 会写入 lastCalculated,因此读取计算值也会修改独立状态,将副作用与惰性 getter 的读取时机耦合。

use-double.ts

import { computed, ref } from 'vue';
export function useDouble() {
  const count = ref(0);
  const lastCalculated = ref(0);
  const doubled = computed(() => {
    const next = count.value * 2;
    lastCalculated.value = next;
    return next;
  });
  return { count, doubled, lastCalculated };
}

正确示例

getter 只返回派生数字。独立侦听器负责在 count 变化时写入 lastCalculated,也包括初始值。

use-double.ts

import { computed, ref, watch } from 'vue';
export function useDouble() {
  const count = ref(0);
  const lastCalculated = ref(0);
  const doubled = computed(() => count.value * 2);
  watch(count, next => { lastCalculated.value = next * 2; }, { immediate: true });
  return { count, doubled, lastCalculated };
}

配置(Vite+)

CLI 当前不会输出这个诊断代码,因此这里没有可启用它的 CLI 规则配置。

相关页面

公开说明

跨文件规则索引