在form wire:submit.prevent之后刷新相同的livewire组件



请在表单提交后刷新相同的组件。有一个if语句允许表单在组件中显示。我想刷新整个组件,以免在提交后再次显示表单。

我已经尝试过发射,但我认为它不适用于相同的组件。

Livewire组件

<?php

namespace AppHttpLivewire;

use AppLesson;
use AppQuestion;
use AppQuestionsOption;
use AppTestsResult;
use LivewireComponent;

class LessonTest extends Component
{

public $test_result;
public $lesson;
public $test_exists;
public array $question = [];

//protected $listeners = ['testDone' => 'render'];

public function mount($test_exists, $lesson, $test_result)
{
$this->lesson = $lesson;

$this->test_exists = $test_exists;
$this->test_result = $test_result;
}

public function lessonTest()
{

$lesson = Lesson::where('slug', $this->lesson->slug)->firstOrFail();
$answers = [];
$test_score = 0;
foreach ($this->question as $question_id => $answer_id) {
$question = Question::find($question_id);
$correct = QuestionsOption::where('question_id', $question_id)
->where('id', $answer_id)
->where('correct', 1)->count() > 0;
$answers[] = [
'question_id' => $question_id,
'option_id' => $answer_id,
'correct' => $correct,
];
if ($correct) {
$test_score += $question->score;
}
/*
* Save the answer
* Check if it is correct and then add points
* Save all test result and show the points
*/
}
$test_result = TestsResult::create([
'test_id' => $this->lesson->test->id,
'user_id' => Auth::id(),
'test_result' => $test_score,
]);

$test_result->answers()->createMany($answers);

$this->reset(['question']);


$this->emit('testDone');



}


public function render()
{
return view('livewire.lesson-test');
}
}

Livewire刀片视图

<div>
@if ($test_exists)
<hr />
<h3>Test: {{ $lesson->test->title }}</h3>
@if (!is_null($test_result))
<div class="alert alert-info">Your test score: {{ $test_result->test_result }} /
{{ $lesson->test->questions->count() }}</div>
@else
<form wire:submit.prevent='lessonTest' action="{{ route('lessons.test', [$lesson->slug]) }}"
method="post">
{{ csrf_field() }}
@foreach ($lesson->test->questions as $question)
<b>{{ $loop->iteration }}. {{ $question->question }}</b>
<br />
@foreach ($question->options as $option)
<input type="radio" wire:model='question.{{ $question->id }}'
name="questions[{{ $question->id }}]" value="{{ $option->id }}" />
{{ $option->option_text }}<br />
@endforeach
<br />
@endforeach
<button class="btn btn-success btn-lg refresh" type="submit">Submit</button>
</form>
@endif
<hr />
@endif
</div>

谢谢。我解决了它,我忘记了我之前通过了控制器的测试结果,所以我不得不回忆lessonTest操作中的test_result和test_exist。

$this->test_result = TestsResult::where('test_id', $this->lesson->test->id)
->where('user_id', Auth::id())
->first();
$this->test_exists = true;

最新更新