Как исправить строки моей таблицы в laravel с помощью vuejs?(строки разделяются в другую таблицу)

#laravel #vue.js

#laravel #vue.js

Вопрос:

Я пытаюсь создать таблицу с помощью vuejs и laravel, но строка таблицы / данные разделяются каждая как другая таблица.

Я пытался изменить некоторый код в vue и контроллере, но в итоге получился тот же результат.

Customers.vue

 <template>
    <div>
        <h2>Customer Details</h2>
        <div class="table table-bordered" v-for="customer in customers" v-bind:key="customer.CustomerID">

        <tr>
            <th>ID</th>
            <th>Customer</th>
            <th>Address</th>
            <th>Contact No.</th>
        </tr>
            <tr>
                <td>{{customer.CustomerID}}</td>
                <td>{{customer.Customer}}</td>
                <td>{{customer.Address}}</td>
                <td>{{customer.CustomerContactNo}}</td>
            </tr>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            customers: [],
            customer: {
                CustomerID: '',
                Customer: '',
                Address: '',
                CustomerContactNo: ''
            }, 
            customer_CustomerID:'',
            pagination: {},
            edit: false
        }
    },

    created (){
        this.fetchCustomers();
    },

    methods: {
        fetchCustomers() {
            fetch('api/customers')
                .then(res  => res.json())
                .then(res => {
                   this.customers = res.data;
                });
        }
    }
};
</script>
  

Контроллер (индекс):

 class CustomerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        // Get customer details
        $customers = Customer::orderBy('created_at','desc')->paginate(5);

        //Return collection of Customers as a resource
        return CustomerResource::collection($customers);

    }

  

Я ожидаю, что таблица будет просто одной, а не каждая строка превратится в отдельную таблицу. Спасибо.

Ответ №1:

Это потому, что у вас есть цикл v-for для элемента таблицы, означающий, что он создает новую таблицу для каждого клиента.

  • Переместите директиву v-for в элемент customer tr.

Customers.vue

 <template>
    <div>
        <h2>Customer Details</h2>
        <table class="table table-bordered">
        <tr>
            <th>ID</th>
            <th>Customer</th>
            <th>Address</th>
            <th>Contact No.</th>
        </tr>
            <tr v-for="customer in customers" v-bind:key="customer.CustomerID">
                <td>{{customer.CustomerID}}</td>
                <td>{{customer.Customer}}</td>
                <td>{{customer.Address}}</td>
                <td>{{customer.CustomerContactNo}}</td>
            </tr>
        </table>
    </div>
</template>