【问题标题】:How do I pass a route parameter to Vue.js from Laravel如何从 Laravel 将路由参数传递给 Vue.js
【发布时间】:2016-07-01 17:46:48
【问题描述】:

我有这样的路线来获取带有相关评论的帖子。

Route::get('/api/topics/{category_id}/{title}', function($category_id, $title){
    return App\Topic::with('comments')->where(compact('category_id','title'))->firstOrFail();
});

问题是如何将参数变量传递给 Vue.js?在这种情况下,“category_id”和“title”,因此 Vue 可以获取帖子以及 cmets。

下面是我的 Vue 实例,它给了我这个错误:

main.js:11749Uncaught ReferenceError: category_id is not defined

Vue 实例

new Vue({


el: '#comment',

methods: {

    fetchComment: function (category_id, title) {
        this.$http.get('/api/topics/' + category_id + '/' + title ,function (data) {
            this.$set('topics',data)
        })
    }


},
ready: function () {
    this.fetchComment(category_id, title)
}
}); 

显示某个帖子的方法

public function show($category_id, $title)
{

$topic = Topic::where(compact('category_id','title'))->firstOrFail();

$comments = Comment::where('topic_id',$topic->id)->get();

return view('forums.category', compact('topic','comments'));
}

【问题讨论】:

    标签: laravel laravel-5 vue.js


    【解决方案1】:

    论坛控制器.php

    public function show($category_id, $title) {
        $topic = Topic::where('category_id', $category_id)
            ->where('title', $title)
            ->firstOrFail();
    
        return view('forums.category')
            ->with('topic', $topic);
    }
    

    Javascript

    var category_id = '{{ $topic->cataegory_id }}';
    var title       = '{{ $topic->title }}';
    
    new Vue({
      el: '#comment',
    
      methods: {
        fetchComment: function(category_id, title) {
          this.$http.get('/api/topics/' + category_id + '/' + title, function(data) {
            this.$set('topics', data);
          })
        }
    
    
      },
    
      ready: function() {
        this.fetchComment(category_id, title);
      }
    });
    

    【讨论】:

    • 试图通过帖子中列出的路由从数据库中获取参数
    • 看看这个main.js:11749Uncaught ReferenceError: category_id is not defined, category_id not defined,你在this.fetchComment(category_id, title)中使用,title不被定义为
    • 尝试在方法中使用之前声明 category_id 和标题,例如var category_id = put_here_the_souce_of_category_id,并为标题做,我可以看到完整的代码吗?
    • 这是否意味着Vue实例无法从上面的api中获取数据?
    猜你喜欢
    • 1970-01-01
    • 2016-09-19
    • 2018-06-20
    • 2019-03-03
    • 2018-08-14
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多