Does Vue support reactivity on Map and Set data types?
Vue.js的文档提到了针对普通Javascript对象的智能自动更改跟踪:
When you pass a plain JavaScript object to a Vue instance as its data option, Vue.js will walk through all of its properties and convert them to getter/setters using Object.defineProperty.
由于Javascript的
Vue.js不支持对
功能票进行了一些讨论,并且可以通过用户" inca "来解决:
Sets and Maps are not observable by Vue. In order to use those a€"
either inv-for , or in computed properties, methods, watchers,
template expressions, etc. a€" you need to create a serializable replica
of this structure and expose it to Vue. Here's a naive example which
uses a simple counter for providing Vue with information thatSet is
updated:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 data() {
mySetChangeTracker: 1,
mySet: new Set(),
},
computed: {
mySetAsList() {
// By using `mySetChangeTracker` we tell Vue that this property depends on it,
// so it gets re-evaluated whenever `mySetChangeTracker` changes
return this.mySetChangeTracker && Array.from(this.mySet);
},
},
methods: {
add(item) {
this.mySet.add(item);
// Trigger Vue updates
this.mySetChangeTracker += 1;
}
}This illustrates a kinda hacky but 100% working method for making
non-observable data reactive. Still, in real world cases I ended up
with serialized versions of Sets/Maps (e.g. you'd probably want to
store the modified versions of sets/maps in localstorage and thus
serialize them anyway), so no artificial counters/hacks were involved.
据我所知,Vue的反应性跟踪作业。如果您在集合上执行任务,则它应跟踪反应性,例如:
1 2 3 4 5 | methods: { add(item) { this.mySet = new Set(this.mySet.add(item)); } } |
这为您提供了更简洁的代码,但存在一个明显的问题:性能。
只需根据需要选择解决方案即可:)
Vue 3
是的。
Vue 3文档在"深度反应性"和"基本反应性API"中进行了介绍。
另外还有四种" reactive "和" reference "。在使用Vue 3和ES6编码6个月后,我仍在尝试寻找适合我的使用模式。主要问题是,是使用
参考
有一个陷阱。如果一个人在自己的JavaScript中使用
我目前将
反应性
1 | const rve = reactive( new Map() ) |
访问此类不需要
我希望
我也希望名称可以更改,以使它们更接近。
概括
对于Vue 3,最有力的答案是"是"。
但是,开发人员指南可以变得更加简单明了,明确指出选择
编辑:我目前的倾向是