Vue3中数组filter方法,使用reactive不更新界面,而使用ref定义更新界面

Vue3中使用reactive定义数组,对其进行更改不更新界面,也检测不到变化,但数据变了

let todoList = reactive(JSON.parse(localStorage.getItem('todoList')) || [])
...
function clearAllDoneTodo(){
      console.log(todoList) 
      todoList = todoList.filter(todo=>!todo.done)
      console.log(todoList,"@@")
    }

删除跳舞和睡觉事件,输出打印前后的todolist
在这里插入图片描述
在这里插入图片描述

可以看到todolist由Proxy(Array) 变为 [Proxy(Object)…Proxy(Object)]
界面是没有更新的,localStorage也没变,只是todolist变了

下面使用ref定义数据

 let todoList = ref(JSON.parse(localStorage.getItem('todoList')) || [])
 ...
 function clearAllDoneTodo(){
   console.log(todoList.value)
   todoList.value = todoList.value.filter(todo=>!todo.done)
   console.log(todoList.value,"@@")
 }

在这里插入图片描述

删除睡觉和跳舞,可以看到界面已删除且localStorage也同步删除了

在这里插入图片描述
在这里插入图片描述

输出前后todolist,可以看到由Proxy(Array)变为Proxy(Array),且检测到todolist数组变化

watch(todoList,(newV,oldV)=>{
      console.log("todolist被修改了")
      localStorage.setItem('todoList',JSON.stringify(newV))
    },{deep:true})

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值