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 函数  
  };  
};

结果展示:

相关推荐
我星期八休息16 小时前
C++智能指针全面解析:原理、使用场景与最佳实践
java·大数据·开发语言·jvm·c++·人工智能·python
大猫会长16 小时前
docker安装php+apache
java·开发语言
道之极万物灭16 小时前
Go小工具合集
开发语言·后端·golang
梵得儿SHI17 小时前
Java 反射机制深度剖析:性能与安全性的那些坑
java·开发语言·安全·反射·动态代理·性能·反射机制
fsnine17 小时前
Python图形化界面——pyqt5教程
开发语言·python·qt
嵌入式-老费17 小时前
Easyx图形库应用(和lua结合使用)
开发语言·lua
AsiaLYF17 小时前
kotlin中MutableStateFlow和MutableSharedFlow的区别是什么?
android·开发语言·kotlin
IT_陈寒17 小时前
Python+AI实战:用LangChain构建智能问答系统的5个核心技巧
前端·人工智能·后端
Asuncion00717 小时前
Docker核心揭秘:轻量级虚拟化的革命
服务器·开发语言·docker·云原生
袁煦丞17 小时前
MoneyPrinterTurbo一键生成短视频:cpolar内网穿透实验室第644个成功挑战
前端·程序员·远程工作