3 回答
TA贡献1898条经验 获得超8个赞
问题是提交的表单“太快”(backAfterSaveStatus 值未完成与输入的绑定)。使用 $nextTick 以便 Alpine 等待,直到值被正确更改。
<form method="post" class="withBackAfterSave">
@csrf
<div x-data="{
backAfterSaveStatus: '',
backAfterSave () {
this.backAfterSaveStatus = '1';
this.$nextTick(() => { document.querySelector('form.withBackAfterSave').submit() });
}
}">
<input name="backAfterSave" x-bind:value="backAfterSaveStatus">
<div>
<span>
<button x-on:click.prevent="backAfterSave()" type="submit">
Save & back
</button>
</span>
<span>
<button type="submit">
Save
</button>
</span>
</div>
</div>
</form>
TA贡献1830条经验 获得超3个赞
刚刚发布,我可以使用带有自定义名称和给定值的简单按钮。不需要 javascript :)
<button type="submit" name="back-after-submit" value="1">Save</button>
TA贡献1826条经验 获得超6个赞
我不使用x-ref,因为这些按钮位于单独的layouts文件中,所以我无法将其移出x-data范围。我的最终代码:
<div class="pt-5">
<div class="flex justify-end" x-data="{
backAfterSave: 0
}">
<input type="hidden" name="backAfterSave" :value="backAfterSave">
<button type="button"
class="bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
{{ __('Cancel') }}
</button>
<button type="submit"
@click.prevent="backAfterSave=1; $nextTick(() => {
document.querySelector('form.with-back-after-save').submit()
})"
class="ml-3 inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
{{ __('Save & back') }}
</button>
<button type="submit"
class="ml-3 inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-teal-600 hover:bg-teal-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-teal-500">
{{ __('Save') }}
</button>
</div>
</div>
添加回答
举报