vue.js - 通过已知 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 中的任何数据?
解决方案
按 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: {...}})
推荐阅读
- node.js - .sort 是否始终保持项目的时间顺序?
- c - 用于替换数组下标的 C 宏
- java - Javax Servlet - 多部分作为响应
- c++ - regex_match 期间的 error_stack
- excel - Excel VBA,带有评估(MAX(IF))条件的自定义搜索 - 不匹配错误
- typo3 - Fluid Typolink ViewHelper 忽略附加参数属性
- javascript - 在jquery中单击选项卡时禁用单击?
- python - 使数据框列等于另一个时获取 nan
- gmp - 荨麻曲线 25519 基点结果 * 1
- powershell - 无法使用 PowerShell 从 SharePoint 下载大文件