试图解决我的页面在重新加载时出现错误的问题。我有一个客户页面,它在 for 循环中包含一个表格行组件,因此每个客户都有一行。我单击该行,它会呈现 ClientsEdit 组件,从 URL 传递 ID 并过滤我的状态。如果我在 ClientsEdit 组件上刷新页面,则会出现问题。我得到错误Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'client_name')
。这是我的 ClientsEdit 组件中的 js:
export default {
name: 'ClientsEdit',
components: {
ArrowLeftIcon,
FormSection,
CheckIcon,
FormActionMessage,
FormButton
},
props: ['id'],
data() {
return {
formIsProcessing: false,
formRecentlySuccessful: false,
pageTitle: '',
currentClient: {} //I've tried adding the properties to the object here.
};
},
methods: {
...mapMutations('clients', ['SET_CURRENT_CLIENT']),
...mapActions('clients', ['UPDATE_CLIENT']),
updateClientInformation(event) {
this.formIsProcessing = true;
const payload = {
id: this.$route.params.id,
client_name: event.target.clientName.value,
address: event.target.address.value,
city: event.target.city.value,
state: event.target.state.value,
zip: event.target.zip.value,
}
this.UPDATE_CLIENT(payload);
this.formIsProcessing = false;
this.showActionMessage();
},
getCurrentClient() {
this.SET_CURRENT_CLIENT(this.$route.params.id);
this.currentClient = this.currentClientArray[0];
this.pageTitle = this.currentClient.client_name;
},
showActionMessage() {
this.formRecentlySuccessful = true;
setTimeout(() => {
this.formRecentlySuccessful = false;
}, 1500);
}
},
computed: {
...mapState('clients', ['currentClientArray']),
},
created() {
this.getCurrentClient();
}
}
这是我的 clients.js vuex 商店:
import axios from 'axios';
export default {
namespaced: true,
state() {
return {
clientData: [],
currentClientArray: null,
}
},
mutations: {
SET_CLIENT_DATA(state, payload) {
state.clientData.push(payload);
},
SET_CURRENT_CLIENT(state, payload) {
state.currentClientArray = state.clientData.filter((client) => {
return client.id === parseInt(payload);
});
},
EDIT_CLIENT(state, payload) {
const index = state.clientData.findIndex((item) => item.id === parseInt(payload.id));
if(index !== -1) state.clientData.splice(index, 1, payload);
}
},
actions: {
async GET_CLIENTS({commit, state}) {
await axios.get('http://localhost/api/clients').then(resp => {
const rows = resp.data;
rows.forEach((row) => {
const data = {
id: row.id,
client_name: row.client_name,
address: row.address,
city: row.city,
state: row.state,
zip: row.zip,
created_at: row.created_at,
updated_at: row.updated_at,
deleted_at: row.deleted_at
}
commit('SET_CLIENT_DATA', data)
})
});
},
async UPDATE_CLIENT(context, payload) {
await axios.patch(`http://localhost/api/clients/${payload.id}/edit`, payload).then(resp => {
context.commit('EDIT_CLIENT', payload);
})
}
},
getters: {
hasClients(state) {
return state.clientData.length > 0
}
}
}
我已经尝试添加 vuex 持久状态插件,但也许我没有做对,因为即使我出于某种原因重新加载客户端页面时它也没有获得状态,但记住了对我的 ClientsEdit 页面所做的更改。
我只是想知道我的问题的解决方案是否是持久状态插件,我需要继续沿着这条路走下去,直到我可以让它正常工作,或者我在代码中的某个地方做错了什么。只要我不刷新 ClientsEdit 页面,此代码就可以正常工作。