Laravel-Vue应用无表单场景下Axios post请求触发页面刷新如何解决
解决方案
排查全局axios响应拦截器
绝大多数Axios请求完成后自动刷新的场景,都是全局拦截器检测到异常状态码(比如419 CSRF token过期、401未授权)时配置了强制刷新页面的逻辑。你可以先在catch块打印完整的error对象,确认请求是否正常返回,是否触发了拦截器的刷新逻辑。修正单选框绑定的冗余逻辑
你同时给单选框配置了v-model、:checked和@click,属于重复绑定,可能引发未知的状态异常:
v-model已经默认实现了选中状态的双向绑定,不需要额外添加:checked属性;单选框的状态变更事件建议使用@change而非@click,避免点击标签未选中区域时重复触发事件。确认CSRF Token配置
Laravel默认要求所有POST请求携带CSRF Token,需要确认axios已配置自动携带请求头:
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; const token = document.head.querySelector('meta[name="csrf-token"]'); if (token) { window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content; }
检查自定义通知方法逻辑
你调用window.notify时传入了第四个参数true,需要确认该参数是否被定义为操作成功后刷新页面的配置,很多自定义通知组件会预留重载页面的参数位,可先将该参数改为false测试。确认路由响应逻辑
确认settings/update/region-mode路由没有返回302重定向响应,异步请求收到重定向指令也会触发页面跳转刷新。
修正后的HTML代码
<div class="form-group form-inline"> <label class="control-label mr-3" for="status"><strong>{{ __('Region Mode') }}</strong> </label> <div class="form-check form-check-inline"> <label class="form-check-label mr-3"> <input type="radio" name="default_region_mode" v-model="region_mode" @change="updateRegionMode" class="form-check-input" value="single_region" /> {{ __('Single Region') }}<i class="input-frame"></i> </label> </div> <div class="form-check form-check-inline mr-2"> <label class="form-check-label"> <input type="radio" name="default_region_mode" v-model="region_mode" @change="updateRegionMode" class="form-check-input" value="multiple_region" /> {{ __('Multiple Region') }}<i class="input-frame"></i> </label> </div> </div>
修正后的JS方法代码
updateRegionMode() { const value = this.region_mode; this.is_updating = true; axios.post('settings/update/region-mode', { value }) .then(response => { this.is_updating = false; const res = response.data; console.log(res); if (res.code === 200) { window.notify('success', 'Success', res.message, false); } else { window.notify('error', 'Oops !!', res.message); } }) .catch(({ response: error }) => { this.is_updating = false; console.log('完整错误信息:', error); window.errorNotify(error, "Oops !!"); }); }
内容的提问来源于stack exchange,提问作者Xsmael
相关产品推荐
相关产品推荐

