Vue3的reactive赋值问题
Vue3 的 reactive 赋值问题
公司新项目是使用 Vue3(3.2.37) 框架,在编程过程中遇见框架问题,在此记录
问题
先说问题:Vue3 中直接对 reactive 变量本身进行赋值是没有效果的
筛选表单重置功能
1 | // 数据结构 |
我原本的做法是直接给 filterForm 赋值为原来的状态
1 | function reset() { |
但测试之后,发现没有效果,于是改成了单个数据置空,就生效了
1 | function reset() { |
弹窗数据回显
1 | const props = defineProps({ |
我是直接监听 visible 变量,如果弹窗显示,就将数据回显
我原本是直接将 props.data
结构赋值给 modalData,结果没有生效,我使用 vue 插件查看,插件显示 modalData 是一个空对象
console.log
打印,发现数据是有值的,我百思不得其解
1 | watch{ |
查了一下资料,发现直接给 reactive 变量本身赋值是没有效果的
于是我就给 modalData 又套了一层 data,就生效了
1 | let modalData = reactive({ |
解决方案
单个赋值
1
2
3
4
5
6
7
8
9let filterForm = reactive({
createDate: null
})
filterForm.createDate = '2023-7-10'
function reset() {
filterForm.createDate = null
}多套一层
1
2
3
4
5
6
7
8
9
10
11
12const props = defineProps({
data:{
type: Object,
default: {}
}
})
const modalData = reactive({
data:{}
})
modalData.data = { ...props.data }
补充
在查阅资料时发现,reactive 赋值的数组同样有问题,如果需要清空数组不能直接赋值一个空数组,而是要将数组长度设置为 0
1 | let arr = reactive([]) |
Vue 真是一个版本一个坑,属于是 $set
的复刻版了
-
感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 View Room
评论