由渲染组件prop更改vuex存储中数组中对象的值

问题描述 投票:0回答:1

我在vuex存储中有一个对象数组。我将其转到页面并使用组件进行渲染。一切都好我想要的是能够更改特殊对象的值,我使用数据来渲染组件。我希望这是有道理的。我的主要问题是,如何修改数组中的特殊对象

export const state = () => {  return {
villas: [
  {name: 'First', location:'a1', date:2014, rating:4.9}, 
  {name: 'Second', location:'a2', date:2014, rating:4.8}, 
  {name: 'Third', location:'a3', date:2014, rating:4.9}, 
  {name: 'Fourth', location:'a4', date:2014, rating:4.9}, 
  {name: 'Fourth', location:'a5', date:2014, rating:4.9}, 
  {name: 'Fourth', location:'a6', date:2014, rating:4.9}, 
  {name: 'Fourth', location:'a7', date:2014, rating:4.9}, 
  {name: 'Fifth', location:'a8', date:2014, rating:4.9}],  }}

我的页面

<v-layout class="go" row>
          <Gond v-for="villa in villas" :key="villa.name" :name="villa.name" :location="villa.location" :date="villa.date" :rating="villa.rating"/>
</v-layout>

和我的组件

  export default {
props: ['name', 'location', 'date', 'rating'],
data() {
  return {
  }
},
vue.js vuex nuxt
1个回答
0
投票

您将需要创建一个动作和一个变异来更新商店数据

假设别墅名称是唯一的,

创建吸气剂(可选),

getVillaByName: state => {
    return state.villas.filter(villa => villa.name)
}

创建动作

updateVillaByName ({commit }, payload) {
    commit('UPDATE_VILLA_BY_NAME', payload)
}

创建突变

UPDATE_VILLA_BY_NAME (state, updatedVilla) {

  // there are few different ways you can update the array of objects
  // one way is to go like below. Ref - [https://stackoverflow.com/questions/50422357/updating-object-in-array-with-vuex][1]

  state.villas = [
     ...state.villas.filter(element => element.name !== updatedVilla.name),
     updatedVilla
  ]
}

例如,在您的组件中,>

methods: {
  updateVillaLocation (newLocation) {

    let villa = this.$store.getters.getVillaByName(this.name)

    villa.location = newLocation

    this.$store.commit('updateVillaByName', villa)
  }
}

希望这能回答您的问题:)如果您需要更多指导,请告诉我

© www.soinside.com 2019 - 2024. All rights reserved.