Write operation failed: computed value is readonly问题解决

源代码:

javascript 复制代码
// 封装倒计时逻辑函数
import { computed, ref } from 'vue'
import dayjs from 'dayjs'
export const useCountDown = () => {
    // 1.响应式数据
    const time = ref(0)
    // 格式化时间
    const formatTime = computed(()=>dayjs.unix(time.value).format('mm分ss秒'))
    // 2.开始倒计时的函数
    const start = (currentTime) => {
        // 倒计时逻辑
        formatTime.value = currentTime 
        setInterval(() => {
            formatTime.value--
        }, 1000);
    }
    return {
        formatTime,
        start
    }
}

解析:

上述代码中的错误 Write operation failed: computed value is readonly 是因为尝试直接修改一个 computed 属性的值。在 Vue 3 中,computed 属性是只读的,不能直接给它赋值。修复这个问题,需要通过修改底层响应式数据来影响 computed 属性的值。在useCountDown 钩子中,直接修改 time 引用的值,而不是尝试修改 formatTimeformatTime 会根据 time 的变化自动更新。

更改后代码:

将上述代码中待修改的formatTime该为time即可,用time改变,formatTIme承接数据

javascript 复制代码
import { ref, computed, onUnmounted } from 'vue';  
import dayjs from 'dayjs';  
  
export const useCountDown = () => {  
  // 1. 响应式数据  
  const time = ref(0); // 倒计时秒数  
  // 2. 计算属性,用于格式化时间  
  const formatTime = computed(() => dayjs.unix(time.value).format('mm:ss'));  
  
  // 3. 开始倒计时的函数  
  const start = (totalSeconds) => {  
    time.value = totalSeconds; // 设置初始倒计时时间  
    const intervalId = setInterval(() => {  
      if (time.value > 0) {  
        time.value--; // 每秒减少1  
      } else {  
        clearInterval(intervalId); // 时间到,清除定时器  
      }  
    }, 1000);  
  
    // 组件卸载时清除定时器  
    onUnmounted(() => {  
      clearInterval(intervalId);  
    });  
  };  
  
  // 4. 重置倒计时的函数  
  const reset = (totalSeconds) => {  
    time.value = totalSeconds; // 重置倒计时时间  
  };  
  
  return {  
    formatTime,  
    start,  
    reset // 可以选择性地暴露 reset 函数  
  };  
};

结果展示:

相关推荐
tedcloud12313 小时前
UI-TARS-desktop部署教程:构建AI桌面自动化系统
服务器·前端·人工智能·ui·自动化·github
jerryinwuhan16 小时前
基于各城市站点流量的复合功能比较
开发语言·php
UXbot16 小时前
AI原型设计工具如何支持团队协作与快速迭代
前端·交互·个人开发·ai编程·原型模式
迈巴赫车主17 小时前
Java基础:list、set、map一遍过
java·开发语言
ZC跨境爬虫17 小时前
跟着MDN学HTML_day_48:(Node接口)
前端·javascript·ui·html·音视频
南 阳18 小时前
Python从入门到精通day66
开发语言·python
PieroPc19 小时前
CAMWATCH — 局域网摄像头监控系统 Fastapi + html
前端·python·html·fastapi·监控
十八旬19 小时前
快速安装ClaudeCode完整指南
开发语言·windows·python·claude
前进的李工19 小时前
EXPLAIN输出格式全解析:JSON、TREE与可视化
开发语言·数据库·mysql·性能优化·explain
Byron Loong20 小时前
【c++】为什么有了dll和.h,还需要包含lib
java·开发语言·c++