如何使用vue.js在laravel 5.7中保存类别

时间:2018-11-26 22:27:00

标签: vue.js laravel-5.7

我将Laravel 5.7与vuejs结合使用,我试图显示MySQL类别表中的parent_id。我想传递名称并获得所有子类别,而与父类别无关。

我的刀片

<form action="{{ route('categories.store') }}" method="post">
    @csrf
    <div class="form-group">
        <label for="name">name:</label>
        <input type="text" id="name" class="form-control" v-model="name">
    </div>
    <div class="form-group">
        <label for="sub_category">category</label>
        <select id="sub_category" v-model="parent_id" class="form-control">
            <option data-display="main category" value="0">main category</option>
            <option v-for="category in categories" :value="category.id">@{{ category.name }}</option>
        </select>
    </div>
    <div class="form-group">
        <button type="button" @click="addCategory()"  class="btn btn-info">save</button>
    </div>
</form>

web.php

Route::group(['namespace' => 'Admin', 'prefix' => 'admin'],function (){
    $this->get('panel', 'PanelController@index')->name('panel.index');
    $this->resource('categories', 'CategoryController');
});

我的Vue

addCategory: function () {
    axios.post(route('categories.store'), {
        name: this.name,
        parent_id: this.parent_id,
    }).then(response => {
        this.categories.push({'name': response.data.name, 'id': response.data.id});
    }, response => {
        this.error = 1;
        console.log('Errors');
    });
}

CategoryController

public function store(Request $request)
{
    $category = new Category();
    $category->name = $request->name;
    $category->parent_id = $request->parent_id;
    if ($category->save()) {
        return $category;
    }
}

我首先在控制台中看到此错误

Vue js

VVue

我得到405错误。

405 error

1 个答案:

答案 0 :(得分:1)

  1. 从提交按钮中删除@click
  2. 从表单操作中删除路线...,并将其设置为#
  3. @submit="addCategory()"添加到表单
  4. axios.post中添加不带路由功能的路由。

更新: 如果要阻止页面刷新,请在.prevent之后添加@submit