如何从Laravel将路由参数传递给Vue.js [英] How do I pass a route parameter to Vue.js from Laravel

查看:330
本文介绍了如何从Laravel将路由参数传递给Vue.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a route like this to fetch a post with the associated comment.

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可以获取帖子和评论.

The thing is how can I pass a parameter variables to Vue.js?In this case "category_id" and "title",so Vue can fetch the post as well as the comments.

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

Below is my Vue instance which gives me this error:

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'));
}

推荐答案

ForumsController.php

ForumsController.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

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);
  }
});

这篇关于如何从Laravel将路由参数传递给Vue.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆