我正在尝试在Nuxt中实现以下逻辑:
我目前遇到的问题是,存储中的getUrl getter方法会被反复调用,直到超过最大调用堆栈为止,而我无法弄清原因。它只是从页面中的计算函数调用的,因此这意味着该计算函数也被重复调用,但是,我仍然不知道为什么。
在我的Vuex商店index.js中,我拥有:
export const state = () => ({
appointments: {}
})
export const mutations = {
SET_APPT: (state, appointment) => {
state.appointments[appointment.id] = appointment.url
}
}
export const actions = {
async setAppointment ({ commit, state }, id) {
try {
let result = await axios.get('https://externalAPI/' + id, {
method: 'GET',
protocol: 'http'
})
return commit('SET_APPT', result.data)
} catch (err) {
console.error(err)
}
}
}
export const getters = {
getUrl: (state, param) => {
return state.appointments[param]
}
}
在我的页面组件中,我有:
<template>
<div>
<section class="container">
<iframe :src="url"></iframe>
</section>
</div>
</template>
<script>
export default {
computed: {
url: function (){
let url = this.$store.getters['getUrl'](this.$route.params.id)
return url;
}
}
</script>
从页面中的单独组件调用setAppointments操作,该组件通过onSubmit方法向用户询问ID:
data() {
return {
appointment: this.appointment ? { ...this.appointment } : {
id: '',
url: '',
},
error: false
}
},
methods: {
onSubmit() {
if(!this.appointment.id){
this.error = true;
}
else{
this.error = false;
this.$store.dispatch("setAppointment", this.appointment.id);
this.$router.push("/search/"+this.appointment.id);
}
}
答案 0 :(得分:0)
我不确定100%导致多次通话的原因。但是,正如评论中所建议的那样,我现在实现了一个我保持最新状态的selectedAppointment对象
我还创建了一个单独的突变,用于在用户请求其他URL时更新selectedAppointment对象,因此,如果已经检索到URL,则可以使用此突变来切换选定的URL。
SET_APPT: (state, appointment) => {
state.appointments = state.appointments ? state.appointments : {}
state.selectedAppointment = appointment.url
state.appointments = { ...state.appointments, [appointment.appointmentNumber]: appointment.url }
},
SET_SELECTED_APPT: (state, appointment) => {
state.selectedAppointment = appointment.url
}
然后,getUrl getter(将其名称更改为url)看起来就像:
export const getters = {
url: (state) => {
return state.selectedAppointment
}
}
感谢您的帮助。