使用Vue js和Laravel REST API。数据库为mysql。但是当尝试显示ContactList时,它没有显示在这里。web.php
Route::prefix('api')->group(function() {
//get contact
Route::get('getContacts','ContactController@getContacts');
});
ContactController.php
class ContactController extends Controller
{
public function getContacts() {
$contacts = Contact::all();
return $contacts;
}
}
ContactList.vue
<tbody v-for="contact in contacts" :key="contact.id">
<tr>
<th scope="row">{{ contact.id}}</th>
<td>{{ contact.name}}</td>
<td>{{ contact.email}}</td>
<td>{{ contact.designation}}</td>
<td>{{ contact.contact_no}}</td>
<td><button class="btn btn-danger btn-sm">Delete</button></td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
name:'Contact',
created() {
this.loadData();
},
methods: {
loadData() {
let url = this.url + '/api/getContacts';
this.axios.get(url).then(response => {
this.contacts = response.data
console.log(this.contacts);
});
},
mounted() {
console.log('Contact List Component Mounted');
},
data() {
return {
url: document.head.querySelector('meta[name="url"]').content,
contacts:[]
}
}
}
}
</script>
控制台显示以下错误**[警告]:属性或方法"contacts"不是在实例上定义的,而是在呈现期间引用的。通过初始化属性,确保该属性是可响应的,无论是在data选项中,还是对于基于类的组件。见:https://v2.vuejs.org/v2/guide/reactivity.html Declaring-Reactive-Properties .
中
——比;在资源/js/组件/ContactList.vue* *
在Laravel端以正确的格式发送响应
$contacts = Contact::all();
$data['contacts'] = $contacts;
return response()->json(['status' => true, 'message' => 'Contacts collected', 'data' => $data]);
Vue.js一边
let url = this.url + '/api/getContacts';
this.axios.get(url).then(response => {
this.contacts = response.data.data.contacts
});