#javascript #json #vue.js #vuex #vue-router
#javascript #json #vue.js #vuex #vue-router
Вопрос:
У меня есть компонент Vue, который перечисляет запросы на обслуживание из базы данных.
<template>
<div>
{{ maintenance_requests }}
</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
export default {
computed: {
...mapGetters({
maintenance_requests: 'maintenance/maintenances',
}),
},
methods: {
...mapActions({
getMaintenanceRequests: 'maintenance/getMaintenanceRequests',
}),
},
mounted () {
this.getMaintenanceRequests()
}
}
</script>
Это мой магазин Vuex
import axios from 'axios'
export default {
namespaced: true,
state:{
maintenance_requests: [],
},
getters:{
maintenances (state) {
return state.maintenance_requests.sort((a,b) => b.date_created - a.date_created)
},
mutations:{
PUSH_MAINTENANCES (state, data) {
state.maintenance_requests.push(...data)
},
actions:{
async getMaintenanceRequests ({ commit }) {
let response = await axios.get('/api/maintenance/requests')
commit('PUSH_MAINTENANCES', response.data.data)
}
}
},
Приведенный выше код выводит список обслуживания следующим образом:
{"maintenance_id": 1, "type": "Water problems", "Description": "I have had no water for 2 days now" },
{"maintenance_id": 2, "type": "Electricity problems", "Description": "My bulb is faulty" },
{"maintenance_id": 3, "type": "Roof problems", "Description": "My roof, in the guest bedroom is leaking" },
Я также использую маршрутизатор Vue
import AppMaintenanceForm from './components/maintenance/AppMaintenanceForm.vue'
import AppListMaintenanceRequests from './components/maintenance/AppListMaintenanceRequests.vue'
export const routes = [
{
path: 'list/maintenance/requests',
component: AppListMaintenanceRequests,
name: 'ListMaintenanceRequests'
},
{
path: '/maintenance/form',
component: AppMaintenanceForm,
name: 'MaintenanceForm'
},
]
И проблема в том, что каждый раз, когда я переключаю маршрут. Например, из формы обслуживания в список запросов на обслуживание я получаю дубликат запросов на обслуживание.
Вместо того, чтобы получить это:
{"maintenance_id": 1, "type": "Water problems", "Description": "I have had no water for 2 days now" },
{"maintenance_id": 2, "type": "Electricity problems", "Description": "My bulb is faulty" },
{"maintenance_id": 3, "type": "Roof problems", "Description": "My roof, in the guest bedroom is leaking" },
Я понимаю это:
{"maintenance_id": 1, "type": "Water problems", "Description": "I have had no water for 2 days now" },
{"maintenance_id": 2, "type": "Electricity problems", "Description": "My bulb is faulty" },
{"maintenance_id": 3, "type": "Roof problems", "Description": "My roof, in the guest bedroom is leaking" },
{"maintenance_id": 1, "type": "Water problems", "Description": "I have had no water for 2 days now" },
{"maintenance_id": 2, "type": "Electricity problems", "Description": "My bulb is faulty" },
{"maintenance_id": 3, "type": "Roof problems", "Description": "My roof, in the guest bedroom is leaking" },
и при каждом последующем переключении маршрута он продолжает дублироваться.
{"maintenance_id": 1, "type": "Water problems", "Description": "I have had no water for 2 days now" },
{"maintenance_id": 2, "type": "Electricity problems", "Description": "My bulb is faulty" },
{"maintenance_id": 3, "type": "Roof problems", "Description": "My roof, in the guest bedroom is leaking" },
{"maintenance_id": 1, "type": "Water problems", "Description": "I have had no water for 2 days now" },
{"maintenance_id": 2, "type": "Electricity problems", "Description": "My bulb is faulty" },
{"maintenance_id": 3, "type": "Roof problems", "Description": "My roof, in the guest bedroom is leaking" },
{"maintenance_id": 1, "type": "Water problems", "Description": "I have had no water for 2 days now" },
{"maintenance_id": 2, "type": "Electricity problems", "Description": "My bulb is faulty" },
{"maintenance_id": 3, "type": "Roof problems", "Description": "My roof, in the guest bedroom is leaking" },
Как мне избавиться от этого дублирования? Спасибо.
Ответ №1:
Я думаю, вы можете внести некоторые небольшие изменения в свой vuex, я предложу несколько вариантов, а затем вы проверите, что для вас лучше, хорошо?
- Первое изменение — проверить, существует ли состояние, затем игнорировать повторный запрос чего-то подобного:
actions: {
async getMaintenanceRequests ({ commit, state }) {
if(state.maintenance_requests.length) return // this will ignore that maintenence is length > 0
let response = await axios.get('/api/maintenance/requests')
commit('PUSH_MAINTENANCES', response.data.data)
}
}
- Другое дело, что ваша мутация, это толкает ваш запрос внутрь state.maintenance_requests, это означает, что вы добавите все новые элементы вместе с существующими элементами. Итак, если вам нужно заменить все значения, я рекомендую вам обновить свою мутацию для чего-то подобного:
mutations: {
PUSH_MAINTENANCES (state, data) {
state.maintenance_requests = data
},
},
- И последнее, вам не нужны set …data, потому что это не имеет смысла. … когда вы используете это, вы будете дублировать все свои данные. некоторые думают так:
This means that the code below will result in you having an array with duplicate elements.
const numbers1 = [1, 2, 3, 4, 5];
const numbers2 = [ ...numbers1, 1, 2, 6,7,8]; // this will be [1, 2, 3, 4, 5, 1, 2, 6, 7, 8]
подумайте.
Ответ №2:
Вы нажимаете на массив, а не устанавливаете его. Попробуйте это:
PUSH_MAINTENANCES (state, data) {
state.maintenance_requests = data;
}
В противном случае он продолжает добавлять данные каждый раз.