【问题标题】:pass parameter in URL using vuejs and laravel使用 vuejs 和 laravel 在 URL 中传递参数
【发布时间】:2019-09-22 13:55:57
【问题描述】:

我想使用 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路由器:

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

谢谢。 希望你能帮助我。

【问题讨论】:

    标签: laravel vue.js laravel-5 vuejs2


    【解决方案1】:

    一切都设置好了,只是你的 show 方法应该用 JSON 响应:

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

    【讨论】:

    • 我不这么认为,所以我会编辑我的帖子以添加 vue 路由器
    • 再次,当您的组件中有export default 时,您不必在require() 之后添加.default。顺便说一下,我认为你应该逐步调试,首先在 created() 方法中的 alert(id) 来发现问题,以实现是否正确获取参数。
    • 是的,我这样做了,我得到了 id,但我得到的是 HTML 类型的内容而不是 json 内容。所以这意味着我猜该请求尚未发送到控制器
    • @HichemNeggaz 请尝试重构您的代码。 created() 函数在 methods{} 属性中时不会触发 vue 的事件
    • @Hichem Neggaz 获得 HTML 类型的结果并不意味着请求尚未发送!这意味着您的控制器没有以正确的方式响应。在您的show() 方法中通过return response()-&gt;json(Specialite::findOrFail($id),Response::HTTP_OK); 返回值
    【解决方案2】:

    首先,我看不到 this.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 |
    
    

    附:如果您不发送任何附加文件,则无需创建表单对象,Laravel 和 axios 将在 ajax 请求默认情况下恢复为使用 JSON。

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

    function show($id) {
    
      return Specialite::findOrFail($id);
    
    }
    

    Fail 将返回一个 400+ 的标头,而该标头又可以由 axsios .catch 处理

    .catch( error =&gt; { console.log(error.response.message) } )

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

    .catch( error =&gt; { console.log(error.response.data.errors) } )

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

    data() {
    
        return {
    
            form: {
                id:'',
                name:'',
                user_id:'',
                bio:''
            },
    
        }
    }
    
    ...
    
    axios.post('/api/specialite',this.form).then(...);
    
    

    【讨论】:

      【解决方案3】:

      我相信代码运行良好。这是 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>

      【讨论】:

        猜你喜欢
        • 2018-02-05
        • 2015-12-10
        • 2020-12-20
        • 1970-01-01
        • 1970-01-01
        • 2016-02-21
        • 1970-01-01
        • 2020-05-21
        • 1970-01-01
        相关资源
        最近更新 更多