[英]How to pass an array from Laravel controller to Vue.js component
我想将一个名为hours
的数组从 Laravel controller 传递给 Vue.js 组件,但由于某种原因它不起作用。 正如您在以下代码中看到的那样,我正在尝试在位于组件内部的 select 中动态创建选项,但由于某些原因,我在该数组中看不到任何选项。 在视图中,我创建了一个<p>
来检查从 controller 返回的数组是否正确,最后它是正确的,因为在视图中我能够看到数组的第二个值。 但由于某些原因,我无法可视化组件内数组的值。
这是我的 controller 代码:
$open_at = '00:00';
$close_at = '23:45';
$time = new DateTime($open_at);
$close = new DateTime($close_at);
while ($time < $close) {
$hours[] = $time->format('H:i');
$time->modify('+15 minutes');
}
return view('create')->with('hours', $hours);
这是我的视图代码:
@extends('layouts.app')
@section('content')
<div class="container">
<div id="app">
<create-form :hours="hours"></create-form>
</div>
<p>
{{ $hours[1] }}
</p>
</div>
@endsection
这是模板组件内的代码:
<div class="form-group">
<label for="start">Start Hour:</label>
<select class="form-control" id="start">
<option v-for="hour in hours" :key="hour.id">
{{ hour }}
</option>
</select>
</div>
这是我的 export_default:
export default {
props: ['hours[]'],
mounted() {
console.log('Component mounted.');
this.loadUsers();
this.loadRooms();
},
data: function() {
return {
users: [],
rooms: []
}
},
methods: {
loadUsers: function() {
axios.get('api/users')
.then((response) => {
this.users = response.data.data;
})
.catch(function(error) {
alert('noviva');
console.log(error);
});
},
loadRooms: function() {
axios.get('api/rooms')
.then((response) => {
this.rooms = response.data.data;
})
.catch(function(error) {
alert('noviva');
console.log(error);
});
}
}
}
我在控制台中可视化以下警告:
Property or method "hours" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
可以帮忙?
您的 props 属性的定义与 $hours 传递给组件的名称不匹配
props: ['hours'],
同样,您在id
中构建 hours[] 的方式没有小时数,因此当您尝试时模板会给出另一个错误:key="hour.id
您必须在 controller 中构造小时数组,以便每个条目都有一个 id,或者(不推荐)您可以使用 v-for 循环中的索引作为键
<div class="form-group">
<label for="start">Start Hour:</label>
<select class="form-control" id="start">
<option v-for="(hour, index) in hours" :key="index">
{{ hour }}
</option>
</select>
</div>
PHP arrays 和对象可以通过 json 编码它们作为道具传递给 javascript/vue
//Using the blade helper @json
<div id="app">
<create-form :hours='@json($hours)'></create-form>
</div>
//OR using json_encode()
<div id="app">
<create-form :hours="{{ json_encode($hours) }}"></create-form>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.