使用vuejs和laravel在URL中传递参数

时间:2019-05-04 05:08:23

标签: laravel vue.js laravel-5 vuejs2

我想使用vuejs在laravel中显示具有特定ID的数据。 我从链接获取ID,但似乎没有请求发送到控制器。 api.php:

    <?php

use Illuminate\Http\Request;


Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::resource('user','API\UserController');
Route::resource('departement','API\DepartementController');
Route::resource('specialite','API\SpecialiteController')->parameters(['specialite'=>'id']);

我的控制器:

public function show($id)
    {
        $specialite=Specialite::with('dep')->findOrFail($id);
        $spec = Specialite::with('dep')->where('id',$specialite)->get();
        return $spec;
    }

我的观点:

<script>
    export default {

        data(){
        return{
        specialites:{},
        form: new Form({
            id:'',
            name:'',
            user_id:'',
            bio:''
        }),
        id:0,
        }

        },

    methods: {
        loadspecialite(){
        //axios.get('api/user').then(({data})=>(this.enseignants=data.data));
        axios.get('api/specialite/'+this.id).then(response=>{this.specialites=response.data;});
    },
        created() {
            this.id=this.$route.params.id;
            this.loadspecialite();
            Fire.$on('AfterCreate',()=>{
            this.loadspecialite();

            })

        }
    }
</script>

Vue-router:

 let routes = [
  { path: '/Profile/:id', component: require('./components/a.vue').default },
]

谢谢。 希望你能帮到我。

3 个答案:

答案 0 :(得分:0)

所有设置都很好,只是您的show方法应该以JSON响应:

use Illuminate\Http\Response;

function show($id) {
    result = Specialite::findOrFail($id);
    return response()->json($result,Response::HTTP_OK);
}

答案 1 :(得分:0)

首先,我不知道this.id将如何承载路由器创建的ID,因此不能保证路由器路由后会触发该ID。

调用时,您的loadspecialite应该从currentRoute获取值,我认为var有点错误:

let id = this.$router.currentRoute.params.id;

您的路线资源应为:

Route::resource('specialite','API\SpecialiteController');

请求uri为:

axios.get(`/api/specialite/${id}`).then(...)

您可以使用SSH终端运行控制台命令来找到Laravel中所有已注册路由的确切uri路径:php artisan route:list

这应该产生以下内容:

+--------+-----------+----------------------------------+------------------------+------------------------------------------------------------------------+--------------+
| Domain | Method    | URI                              | Name                   | Action                                                                 | Middleware   |
+--------+-----------+----------------------------------+------------------------+------------------------------------------------------------------------+--------------+
|        | GET|HEAD  | api/specialite                   | api.specialite.index   | App\Http\Controllers\API\ApplicationController@index                   | api,auth:api |
|        | POST      | api/specialite                   | api.specialite.store   | App\Http\Controllers\API\ApplicationController@store                   | api,auth:api |
|        | GET|HEAD  | api/specialite/create            | api.specialite.create  | App\Http\Controllers\API\ApplicationController@create                  | api,auth:api |
|        | GET|HEAD  | api/specialite/{specialite}      | api.specialite.show    | App\Http\Controllers\API\ApplicationController@show                    | api,auth:api |
|        | PUT|PATCH | api/specialite/{specialite}      | api.specialite.update  | App\Http\Controllers\API\ApplicationController@update                  | api,auth:api |
|        | DELETE    | api/specialite/{specialite}      | api.specialite.destroy | App\Http\Controllers\API\ApplicationController@destroy                 | api,auth:api |
|        | GET|HEAD  | api/specialite/{specialite}/edit | api.specialite.edit    | App\Http\Controllers\API\ApplicationController@edit                    | api,auth:api |

P.S。如果您不发送任何附件,则无需创建表单对象,Laravel和axios将默认情况下对ajax请求使用JSON。

默认情况下,Laravel将返回JSON对象,以响应直接从控制器上的资源进行的JSON ajax调用:

function show($id) {

  return Specialite::findOrFail($id);

}

失败将返回400+标头,而axsios .catch可以处理该标头

.catch( error => { console.log(error.response.message) } )

可以通过以下方式访问验证消息中的Laravel:

.catch( error => { console.log(error.response.data.errors) } )

Axios将发布对象/数组作为JSON请求:

data() {

    return {

        form: {
            id:'',
            name:'',
            user_id:'',
            bio:''
        },

    }
}

...

axios.post('/api/specialite',this.form).then(...);

答案 2 :(得分:0)

我确实认为代码运行正常。这是vue组件对象中的格式错误。基本上,您的created()处理函数位于应有的方法中,因此创建的事件完成后将不会对其进行处理。

// your code snippet where there is an issue
methods: {
    loadspecialite(){
    //axios.get('api/user').then(({data})=>(this.enseignants=data.data));
    axios.get('api/specialite/'+this.id).then(response=>{this.specialites=response.data;});
}, // end of loadspecialite
    created() {
        this.id=this.$route.params.id;
        this.loadspecialite();
        Fire.$on('AfterCreate',()=>{
        this.loadspecialite();

        })

    } // end of created
} //end of methods

您应该做的就是从方法中删除created(),然后再次检查函数的语法。

const Foo = {
  template: '<div>foo</div>'
}
const Bar = {
  template: '<div><span> got {{form}}</span></div>',
  data() {
    return {
      specialites: {},
      form: 'fetching...',
      id: 0,
    }

  },

  methods: {
    loadspecialite() {
     // test method for getting some data
      axios.get('https://httpbin.org/anything/' + this.id)
        .then(response => {
          this.form = response.data.url;
        }).catch(error => {
          console.error(error)
        })
    },
  }, // <- this is the end of methods {}
  
  /**
   *  Created method outside of methods scope
   */
  created() {
    this.id = this.$route.params.id;
    this.loadspecialite();
  }
}


// rest is vues demo router stuff
const routes = [{
    path: '/foo',
    component: Foo
  },
  {
    path: '/bar/:id',
    component: Bar
  }
]
const router = new VueRouter({
  routes // short for `routes: routes`
})
const app = new Vue({
  router
}).$mount('#app')
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Vue Routed</title>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
   <style>
       button {
      padding: 0.75rem;
      background: #eee;
      border: 1px solid #eaeaea;
      cursor: pointer;
      color: #000
    }

    button:active {
      color: #000;
      box-shadow: 0px 2px 6px rgba(0,0,0,0.1);
    }

   </style>
</head>

<body>

  <div id="app">
    <h1>Hello App!</h1>
    <p>
      <span> Click a button </span>
      <router-link to="/foo"><button>Go to Foo</button></router-link>
      <router-link to="/bar/3"><button>Go to Where it will get the data</button></router-link>
    </p>
    <!-- route outlet -->
    <!-- component matched by the route will render here -->
    <router-view></router-view>
  </div>

</body>

</html>