目标:尝试构建通过API调用获得的对象数组。当我调用API时,它返回一个对象,我想构建一个选项来存储该结果,然后进行新的调用。
问题:每当我对API进行新调用时,我存储的原始对象都会自动更新。
我尝试在不使用Vuex的情况下都执行此操作,但是无论哪种方式,我都遇到相同的问题。我数组中的每个项目最终都会对API返回的新信息产生反应。我在这里扮演着许多不同的角色,在这里我将分享我认为对问题至关重要的内容。
商店:
export default new Vuex.Store({
state: {
activePlayers: []
},
mutations: {
addPlayer (state, newPlayer) {
state.activePlayers.push(newPlayer)
}
},
actions: {
}
})
核心应用
<template>
<div id="app">
<FetchPlayer
v-on:doFetchPlayer="doFetchPlayer">
</FetchPlayer>
<ShowPlayer
:player="player"
:seasons="seasons">
</ShowPlayer>
<Compare></Compare>
</div>
</template>
<script>
import FetchPlayer from './components/FetchPlayer.vue'
import ShowPlayer from './components/ShowPlayer.vue'
import Compare from './components/Compare.vue'
export default {
name: 'app',
data: function() {
return {
player: {}
}
},
components: {
FetchPlayer,
ShowPlayer,
Compare
},
methods: {
doFetchPlayer: function (playerAttr) {
var url = this.$apiURL
this.$http
.get(url, {headers: this.$apiHeaders})
.then(response => (this.player = response))
.then(this.doFetchSeasons(playerAttr.platform))
}
}
}
</script>
动作模块
<template>
<div class="homeModule" v-if="playerStats.playerName">
<div class="lifetimeStats">
<!-- Data Display -->
</div>
<div class="actionPanel">
<button @click="addPlayer()">+ Compare</button>
</div>
</div>
</template>
<script>
export default {
name: 'ShowPlayer',
props: {
player: {
type: Object,
required: true
}
},
data: function() {
return {
profile: {},
playerStats: {
id: null,
playerName: null,
title: null,
data: {}
}
}
}
watch: {
player: function() {
this.getProfile()
}
},
methods: {
getProfile: function() {
var playerID = this.player.data.data[0].id
var url = this.$apiURL
this.$http
.get(url, {headers: this.$apiHeaders})
.then(response => (this.profile = response))
.then(this.getPlayerStats)
},
getPlayerStats: function() {
var gameMode = this.teamMode
if (this.isFpp) {
gameMode = gameMode + '-fpp'
}
this.playerStats.id = this.profile.data.data.relationships.player.data.id + this.selectedSeason
this.playerStats.playerName = this.player.data.data[0].attributes.name
this.playerStats.title = this.playerStatsTitle
this.playerStats.data = this.profile.data.data.attributes.gameModeStats[gameMode]
},
addPlayer () {
this.$store.commit('addPlayer', this.playerStats)
}
}
}
</script>
我基本上希望“ activePlayers”是一个哑数组,而不会对“ player”或“ playerStats”中的活动信息所做的更改做出反应。最好的方法是什么?
答案 0 :(得分:1)
尝试使用Object.assign(targetObj,srcObj)
来避免更改原始对象或数组,如果要为另一个数组分配数组,请使用以下语句:
this.targetArr=originArr.slice();
Object.assign
也适用于数组,因为它们也是对象。