[英]Adding new item to an array of a reactive object replaces all items in the array. Why?
The main problem is in the title.主要问题在于标题。 My guess would be that the ref() and reactive() are somehow messing with each other, I just don't know how and what I could do about it.
我的猜测是 ref() 和 reactive() 以某种方式相互混淆,我只是不知道如何以及我能做些什么。
The component using the store:使用商店的组件:
<script setup>
import { ref } from "vue";
import { store } from "@/store.js";
const game = ref({
date: null,
location: null,
length: null,
});
</script>
<template>
<form @submit.prevent="store.addGame(game)">
<input v-model="game.date" type="date" required />
<input v-model="game.location" type="text" placeholder="Location" required />
<input v-model="game.length" type="number" placeholder="Length (in minutes)" required />
<button class="button" type="submit">Submit ✔</button>
</form>
</template>
The problem occurs in the store, in the games array, after I add a second or more items...问题出现在商店中,在游戏数组中,在我添加第二个或更多项目后......
store.js:商店.js:
import { reactive } from "vue";
export const store = reactive({
games: [],
addGame(game) {
this.games.push(game);
console.log(this.games);
}
});
The reason is because all the objects that you push inside games
share the same reference.原因是您在
games
中推送的所有对象都共享相同的引用。 To fix this, do this change in store.js
要解决此问题,请在
store.js
中进行此更改
import { reactive } from "vue";
export const store = reactive({
games: [],
addGame(game) {
this.games.push({...game}); // line changed
console.log(this.games);
}
});
It's not "replace", all the game
reference to the same reactive variable defined in const game = ref()
.它不是“替换”,所有
game
都引用了const game = ref()
中定义的同一个反应变量。
Whenever you call store.addGame(game)
, you added the same game
to the store.每当您调用
store.addGame(game)
时,您都会将相同的game
添加到商店中。 Because the game
is reactive, is will automatic implement the latest input value by v-model
.因为
game
是反应式的,所以会通过v-model
自动实现最新的输入值。
If you put another button to check the value in store.如果您放置另一个按钮来检查存储中的值。 Change the input value, and then click Test button, you can see the
store.games
changes too.更改输入值,然后单击测试按钮,您可以看到
store.games
也发生了变化。
<template>
<form @submit.prevent="store.addGame(game)">
<input v-model="game.date" type="date" required />
<input v-model="game.location" type="text" placeholder="Location" required />
<input v-model="game.length" type="number" placeholder="Length (in minutes)" required />
<button class="button" type="submit">Submit ✔</button>
</form>
<button @click="console.log(store.games)">Test</button>
</template>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.