我在vue.js中有点新。通常,使用控制器的显示功能创建显示用户信息的页面非常简单。但是,我现在无所适从,几乎找不到可用的材料来展示如何在vuejs中使用api控制器中的show函数。我已经拥有的如下: Users.vue
<template>
<div class="container">
<div class="row mt-5">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Users Table</h3>
<div class="card-tools">
<button class="btn btn-success" @click="newModal">Add new <i class="fas fa-user-plus"></i></button>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<table class="table table-hover">
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Type</th>
<th>Registered At</th>
<th>Modify</th>
</tr>
<tr v-for="user in users.data" :key="user.id">
<td>{{user.id}}</td>
<td><a href="#" @click="showUser(user)">{{user.name}}</a></td>
<td>{{user.email}}</td>
<td>{{user.type | upText }}</td>
<td>{{user.created_at | myDate}}</td>
<td>
<a href="#" @click="editModal(user)">
<i class="fa fa-edit"></i>
</a>
/
<a href="#" @click="deleteUser(user.id)">
<i class="fa fa-trash red"></i>
</a>
</td>
</tr>
</tbody></table>
</div>
</div>
<!-- /.card -->
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="addNew" tabindex="-1" role="dialog" aria-labelledby="addNewLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 v-show="editmode" class="modal-title" id="addNewLabel">Edit User info</h5>
<h5 v-show="!editmode" class="modal-title" id="addNewLabel">Add Users</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form @submit.prevent="editmode ? updateUser() : createUser()">
<div class="modal-body">
<div class="form-group">
<input v-model="form.name" type="text" name="name"
placeholder="Name"
class="form-control" :class="{ 'is-invalid': form.errors.has('name') }">
<has-error :form="form" field="name"></has-error>
</div>
<div class="form-group">
<input v-model="form.email" type="text" name="email"
placeholder="email"
class="form-control" :class="{ 'is-invalid': form.errors.has('email') }">
<has-error :form="form" field="email"></has-error>
</div>
<div class="form-group">
<textarea v-model="form.bio" type="text" name="bio"
placeholder="Bio"
class="form-control" :class="{ 'is-invalid': form.errors.has('bio') }"></textarea>
<has-error :form="form" field="bio"></has-error>
</div>
<div class="form-group">
<select v-model="form.type" type="text" name="type"
class="form-control" :class="{ 'is-invalid': form.errors.has('type') }">
<option value="">Select user Role</option>
<option value="user">Employee</option>
<option value="manager">Manager</option>
</select>
<has-error :form="form" field="name"></has-error>
</div>
<div class="form-group">
<input v-model="form.password" type="password" name="password"
placeholder="password"
class="form-control" :class="{ 'is-invalid': form.errors.has('password') }">
<has-error :form="form" field="password"></has-error>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button v-show="editmode" type="submit" class="btn btn-success">Update</button>
<button v-show="!editmode" type="submit" class="btn btn-primary">Create</button>
</div>
</form>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
editmode: false,
users : {},
form: new Form({
id:'',
name : '',
email: '',
password: '',
type: '',
bio: '',
photo: ''
})
}
},
methods: {
getProfilePhoto(){
let photo = (this.form.photo.length > 200) ? this.form.photo : "img/profile/"+ this.form.photo ;
return photo;
},
updateUser(){
this.$Progress.start();
// console.log('Editing data');
this.form.put('api/user/'+this.form.id)
.then(() => {
// success
$('#addNew').modal('hide');
swal.fire(
'Updated!',
'Information has been updated.',
'success'
)
this.$Progress.finish();
Fire.$emit('AfterCreate');
})
.catch(() => {
this.$Progress.fail();
});
},
editModal(user){
this.editmode = true;
this.form.reset();
$('#addNew').modal('show');
this.form.fill(user);
},
newModal(){
this.editmode = false;
this.form.reset();
$('#addNew').modal('show');
},
deleteUser(id){
swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
// Send request to the server
if (result.value) {
this.form.delete('api/user/'+id).then(()=>{
swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
Fire.$emit('AfterCreate');
}).catch(()=> {
swal("Failed!", "There was something wrong.", "warning");
});
}
})
},
loadUsers(){
axios.get("api/user").then(({ data }) => (this.users = data));
},
createUser(){
this.$Progress.start();
this.form.post('api/user')
.then(() =>{
Fire.$emit('AfterCreate');
toast.fire({
type: 'success',
title: 'User created successfully'
})
$('#addNew').modal('hide');
this.$Progress.finish();
})
.catch(() => {
})
}
},
created() {
this.loadUsers();
Fire.$on('AfterCreate', () => {
this.loadUsers();
});
}
}
</script>
UserController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth:api');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// $this->authorize('isAdmin');
if (\Gate::allows('isAdmin') || \Gate::allows('isAuthor')) {
return User::latest()->paginate(5);
}
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users',
'password' => 'required|string|min:6'
]);
return User::create([
'name' => $request['name'],
'email' => $request['email'],
'type' => $request['type'],
'bio' => $request['bio'],
'photo' => $request['photo'],
'password' => Hash::make($request['password']),
]);
}
public function updateProfile(Request $request)
{
$user = auth('api')->user();
$this->validate($request,[
'name' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users,email,'.$user->id,
'password' => 'sometimes|required|min:6'
]);
$currentPhoto = $user->photo;
if($request->photo != $currentPhoto){
$name = time().'.' . explode('/', explode(':', substr($request->photo, 0, strpos($request->photo, ';')))[1])[1];
\Image::make($request->photo)->save(public_path('img/profile/').$name);
$request->merge(['photo' => $name]);
$userPhoto = public_path('img/profile/').$currentPhoto;
if(file_exists($userPhoto)){
@unlink($userPhoto);
}
}
if(!empty($request->password)){
$request->merge(['password' => Hash::make($request['password'])]);
}
$user->update($request->all());
return ['message' => "Success"];
}
public function profile()
{
return auth('api')->user();
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$user = User::findOrFail($id);
$this->validate($request,[
'name' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users,email,'.$user->id,
'password' => 'sometimes|min:6'
]);
$user->update($request->all());
return ['message' => 'Updated the user info'];
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$this->authorize('isAdmin');
$user = User::findOrFail($id);
// delete the user
$user->delete();
return ['message' => 'User Deleted'];
}
public function search(){
if ($search = \Request::get('q')) {
$users = User::where(function($query) use ($search){
$query->where('name','LIKE',"%$search%")
->orWhere('email','LIKE',"%$search%");
})->paginate(20);
}else{
$users = User::latest()->paginate(5);
}
return $users;
}
}
最后,我的api.php看起来像这样:
Route::apiResources(['user' => 'API\UserController']);
// Route::get('user/{user}', 'API\UserController@show');
Route::apiResources(['customer' => 'API\CustomerController']);
Route::apiResources(['supplier' => 'API\SupplierController']);
Route::apiResources(['audit' => 'API\AuditController']);
// Route::apiResources(['salesqoute' => 'API\SalesqouteController']);
Route::get('orderlist', 'API\OrderController@index');
Route::get('profile','API\UserController@profile');
Route::put('profile','API\UserController@updateProfile');
通常在laravel中,该节目将使用数据库中的信息创建一个新页面,而url将类似于url / user / 1,并且该页面将加载页面上的各种信息,具体取决于用户想要显示。如果这里有类似的可能,请告诉我,这对我将是巨大的帮助。稍后我将实现相同的功能,因此好的解释将非常有帮助。
答案 0 :(得分:1)
我会写一个简单的例子
<td><a href="#" @click="showUser(user.id)">{{user.name}}</a></td>
只需在showUser的参数中传递id 然后在showUser方法中
data:function(){
return{
user:{
id:'',
name : '',
email: '',
password: '',
type: '',
bio: '',
photo: ''
}
}
},
methods:{
showUser(id){
axios.get('/api/user/'+id).then((res)=>{
if(res.data.status==true){
this.user= res.data.user;
console.log(res.data.user)
}else{
alert('No User founded with this id')
}
}).catch((err)=>{alert('error')})
}
}
在控制器的show方法中
public function show($id)
{
$user=User::find($id);
if($user){
return response()->json(['status'=>true,'user'=>$user]);
}else{
return response()->json(['status'=>false]);
}
}
希望对您有所帮助。 祝你好运!