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

结果展示:

相关推荐
不会敲代码11 小时前
解密JavaScript内存机制:从执行上下文到闭包的全景解析
javascript
Dimpels1 小时前
CANN ops-nn 算子解读:AIGC 批量生成中的 Batch 处理与并行算子
开发语言·aigc·batch
用户5757303346241 小时前
🌟 从一行 HTML 到屏幕像素:浏览器是如何“画”出网页的?
前端
NEXT062 小时前
React Hooks 进阶:useState与useEffect的深度理解
前端·javascript·react.js
blueSatchel2 小时前
U-Boot载入到DDR过程的代码分析
linux·开发语言·u-boot
sure2822 小时前
React Native应用中使用sqlite数据库以及音乐应用中的实际应用
前端·react native
CHU7290352 小时前
扭蛋机盲盒小程序前端功能设计解析:打造趣味与惊喜并存的消费体验
前端·小程序
前端布道师2 小时前
Web响应式:列表自适应布局
前端
ZeroTaboo2 小时前
rmx:给 Windows 换一个能用的删除
前端·后端
哈里谢顿2 小时前
Vue 3 入门完全指南:从零构建你的第一个响应式应用
vue.js