我在Laravel 9中创建了以下控制器函数
public function select(Request $request): Response
{
// Get all diagnostic events (for selection dropdown)
$diagnosticEvents = DiagnosticEventResource::collection(DiagnosticEvent::all());
// Get all answers for selected diagnostic event
$answers = Answer::select('diagnostic_event_id', 'question_id', 'responder_uuid', 'score')
->where('diagnostic_event_id', $request->event_id)
->get();
// Create responder_uuid list and answers array for selected diagnostic event
$responder_uuids = [];
$answerArray = [];
$questions = QuestionResource::collection(Question::all());
foreach($answers as $answer) {
if (!in_array($answer->responder_uuid, $responder_uuids)) {
$responder_uuids[] = $answer->responder_uuid;
}
if (!array_key_exists($answer->question_id, $answerArray)) {
$answerArray[$answer->question_id] = (object)array_merge(
['question' => $questions[$answer->question_id - 1]->description],
['responders' => []]
);
}
if ($answerArray[$answer->question_id]) {
$answerArray[$answer->question_id]->responders[] = (object)array_merge(
['uuid' => $answer->responder_uuid],
['score' => $answer->score]
);
}
}
// Get responder data for selected diagnostic event
$responders = ResponderResource::collection(Responder::whereIn('uuid', $responder_uuids)->get());
return Inertia::render('Answers/Select', [
'diagnosticEvents' => $diagnosticEvents,
'diagnostic_event_id' => $request->event_id == null ? null : (int)$request->event_id,
'answers' => $answerArray,
'responders' => $responders,
'isSchoolAdmin' => Auth::user()->isSchoolAdmin()
]);
}
和一个以以下代码
开头的ve3模块<script setup>
import AuthenticatedLayout from "@/Layouts/Authenticated";
import BreezeLabel from "@/Components/Label";
import {Inertia} from "@inertiajs/inertia";
import {Head} from '@inertiajs/inertia-vue3';
import {ref, watch} from 'vue';
import Index from "@/Pages/Answers/Index.vue";
const props = defineProps ({
diagnosticEvents: Array, // All diagnostic events (for selection)
diagnostic_event_id: Number, // Id for current diagnostic event
answers: Array, // All answers for selected diagnostic event
questions: Array,
responders: Array,
isSchoolAdmin: Boolean
})
当我运行代码时,我将得到一个警告说无效道具:对道具"答案"的类型检查失败。期望的数组,得到的对象
当我在调试器中查看$answerArray时,它是一个数组但是当我在Chrome DevTools中查看道具时,它显示了答案:{1:{,…}, 2:{,…},…}
代替答案:[1:{,…}, 2:{,…},…]
prop responders也是一个包含在惯性:渲染响应中的数组,但被正确传输响应:[{uuid:…},…]
为什么?我能做些什么来解决这个问题?
问题是$answerArray
是一个关联数组。在内部,惯性将调用PHP的json_encode
,它将把它变成一个对象。你有两个选择:
1。修改answers prop
类型为Object
如果keys
在Vue端对你很重要,可以使用这个
2。从$answerArray
创建一个非关联数组为了让json_encode
保持它作为一个数组。
return Inertia::render('Answers/Select', [
// ...
'answers' => array_values($answerArray),
// ...
]);