首页 > 解决方案 > 通过已知 id 访问 vuex 数据

问题描述

我创建了一个 vuex 存储并存储了我从远程源获取的几行数据。数据实际上是 mysql 表中的行。

数据是这种格式

[{
    "id": "1",
    "property_country": "usa",
    "property_name": "i and m towers",
    "property_stars": "4",
    "property_city": "austin",
    "property_region": "texas",
    "property_type": "serviced partment",
    "date_created": "3563763673",
    "date_updated": "33377363",
    "the_user_id": "1"
}, {
    "id": "2",
    "property_country": "uk",
    "property_name": "eagle towers",
    "property_stars": "5",
    "property_city": "kampala",
    "property_region": "kampala",
    "property_type": "motel",
    "date_created": "3563763673",
    "date_updated": "33377363",
    "the_user_id": "1"
},

我希望能够按 id 访问 vuex 数据,按 id 删除,按 id 更新

到目前为止我可以访问console.log(this.$store.state.properties[1].property_country);

像那样。我从循环数据中知道 id,因此,我希望能够使用已知的 id 来执行一些突变。如何查看 vuex 中的数据是如何存储的,如果我知道行的 id,我如何访问存储在 vuex 中的任何数据?

标签: vue.jsvuex

解决方案


按 ID 获取:

this.$store.state.properties.find(property => property.id == 1).property_country

// OR

getById(id) {
  this.$store.state.properties.find(property => property.id == id)
}
getById(1).property_country // "usa"

按 id 移除

removeById(id) {
  this.$store.state.properties.splice(this.$store.state.properties.findIndex(p=>p.id == id), 1)
}

按 ID 更新:

updateById(id, newObject) {
  this.$store.state.properties[this.$store.state.properties.findIndex(p=>p.id == id)] = JSON.parse(JSON.stringyfy(newObject))
}
// here you have to make some logic to make sure the id still makes sense.

更新单个属性

this.$store.state.properties[this.$store.state.properties.findIndex(p=>p.id == 1)].property_country = "NEW_VALUE"

Vuex 方式

// You can always get data from store using this.$store.state
// But to update, change or remove, you need mutations
mutations: {
  removeById(state, id) {
    state.properties.splice(state.properties.findIndex(p=>p.id == id), 1)
  },
  updateById(state, payload) { // payload = {id: 1, newObject = {..]}
    state.properties[state.properties.findIndex(p=>p.id == payload.id)] = JSON.parse(JSON.stringyfy(payload.newObject))
  }
}

// Use like this
this.$store.commit('removeById', 1)
this.$store.commit('updateById', {id: 1, newObject: {...}})

推荐阅读