VueJs Laravel разбивка на страницы - PullRequest
1 голос
/ 13 июля 2020

У меня проблема с установкой laravel - vue -страницы. Я создаю приложение SPA Crud для некоторого тестирования, и оно не очень хорошо работает с fini sh. Я успешно установил разбиение на страницы в серверной части, но интерфейс довольно грязный. Он всегда дает такие ошибки, как:

[Vue warn]: свойство или метод «laravelData» не определено в экземпляре, но на него ссылаются во время рендеринга. находится в

---> в resources / js / components / CustomerList. vue в resources / js / App. vue

, и вот как это приложение. vue выглядит так:

<template>
  <div id="app">

    <div class="container">
      <MyForm :form="form" @onFormSubmit="onFormSubmit" />
      <Loader v-if="loader" />
      <CustomerList
        :customers="customers"
        @onDelete="onDelete"
        @onEdit="onEdit"
      />

    </div>
  </div>
</template>

<script>
import axios from "axios";
import MyForm from "./components/MyForm";
import CustomerList from "./components/CustomerList";
import Loader from "./components/Loader";

export default {
  name: "App",
  components: {
    MyForm,
    CustomerList,
    Loader
  },
  data() {
    return {
      url: "http://localhost:8000/api/leads",
      leads: [],
      laravelData: {},
      form: { name: "", lastname: "", phoneNumber: "", birthday: "", isEdit: false },
      loader: false
    };
  },
  mounted() {
        // Fetch initial results
        this.getCustomers();
    },
  methods: {
    
    getCustomers(page) {
      this.loader = true;
      if (typeof page === 'undefined') {
          page = 1;
      }
      axios.get('http://localhost:8000/api/leads?page=' + page).then(data => {
        this.laravelData = data.data; 
        this.loader = false;
      });
    },
    
    deleteCustomer(id) {
      this.loader = true;

      axios
        .delete(`${this.url}/${id}`)
        .then(() => {
          this.getCustomers();
        })
        .catch(e => {
          alert(e);
        });
    },
    createCustomer(data) {
      this.loader = true;

      axios
        .post(this.url, {
          name: data.name,
          lastname: data.lastname,
          phoneNumber: data.phoneNumber,
          birthday: data.birthday
        })
        .then(() => {
          this.getCustomers();
        })
        .catch(e => {
          alert(e);
        });
    },
    editCustomer(data) {
      this.loader = true;

      axios
        .put(`${this.url}/${data.id}`, {
          name: data.name,
          lastname: data.lastname,
          phoneNumber: data.phoneNumber,
          birthday: data.birthday
        })
        .then(() => {
          this.getCustomers();
        })
        .catch(e => {
          alert(e);
        });
    },
    onDelete(id) {
      // window.console.log("app delete " + id);

      this.deleteCustomer(id);
    },
    onEdit(data) {
      // window.console.log("app edit ", data);

      this.form = data;
      this.form.isEdit = true;
    },
    onFormSubmit(data) {
      // window.console.log("app onFormSubmit", data);

      if (data.isEdit) {
        // call edit customer
        this.editCustomer(data);
      } else {
        // call create customer
        this.createCustomer(data);
      }
    }
  },
  created() {
    this.getCustomers();
  }
};
</script>

Проблема явно в том, что laravelData не получает необходимые данные, но почему? Вот как выглядит ответ json:

{
    "current_page": 1,
    "data": [
        {
            "id": 3,
            "name": "Rade",
            "lastname": "Ilijev",
            "birthday": "1998-11-21",
            "phoneNumber": 612169456,
            "created_at": "2020-07-13T10:52:58.000000Z",
            "updated_at": "2020-07-13T18:25:49.000000Z"
        },
        {
            "id": 13,
            "name": "asdasd",
            "lastname": "kajsdhaksd",
            "birthday": "1111-11-11",
            "phoneNumber": 29292929,
            "created_at": "2020-07-13T19:04:59.000000Z",
            "updated_at": "2020-07-13T19:04:59.000000Z"
        }
    ],
    "first_page_url": "http://localhost:8000/api/leads?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://localhost:8000/api/leads?page=1",
    "next_page_url": null,
    "path": "http://localhost:8000/api/leads",
    "per_page": 19,
    "prev_page_url": null,
    "to": 5,
    "total": 5
}

Это ошибка, которая возникает в CusomerList. vue

[Vue предупреждение]: Ошибка при рендеринге: «TypeError: Невозможно прочитать данные свойства undefined»

найдено в

---> в resources / js / components / CustomerList. vue в resources / js / App. vue

Вот как выглядит CustomerList. vue:

<template>
<div id="rade-table">
    <div class="table-responsive">
      <table class="table table-dark">
        <thead>
          <tr>
            <th>#</th>
            <th>Name</th>
            <th>PhoneNumber</th>
            <th>Birthday</th>
            <th style="width: 148px;">Action</th>
          </tr>
        </thead>

        <tbody>
          <Customer
            v-for="customer in laravelData.data"
            :key="customer.id"
            :customer="customer"
            @onDelete="onDelete"
            @onEdit="onEdit"
          />
        </tbody>
      </table>
      <pagination
        :data="laravelData" @pagination-change-page="getResults"
      ></pagination>
    </div>
</div>
</template>
<script>
import Customer from "./Customer";
export default {
  name: "CustomerList",
  components: {
    Customer
  },
  props: {
    customers: {
      type: Array
    }
  },
  
  methods: {

    onDelete(id) {
      // window.console.log("customer list delete " + id);
      this.$emit("onDelete", id);
    },
    onEdit(data) {
      // window.console.log("customer list edit " + data);
      this.$emit("onEdit", data);
    }
  }
};
</script>

<style scoped></style>

Вот файл, в котором я отображаю данные клиента как Customer. vue файл

<template>
  <tr>
    <td>{{ customer.id }}</td>
    <td>{{ customer.name }} {{ customer.lastname }}</td>
    <td>{{ customer.phoneNumber }}</td>
    <td>{{ customer.birthday }}</td>
    <td>
      <button class="btn rade-button-rounded-edit" @click="onEdit"><i class='far fa-edit'></i></button>
      <button class="btn rade-button-rounded-delete" @click="onDelete"><i class='far fa-trash-alt'></i></button>
    </td>
  </tr>
</template>

<script>
export default {
  name: "Customer",
  props: {
    customer: {
      type: Object
    }
  },
  methods: {
    onDelete() {
      // window.console.log("customer delete " + this.customer.id);
      this.$emit("onDelete", this.customer.id);
    },
    onEdit() {
      // window.console.log("customer edit " + this.customer.id);
      this.$emit("onEdit", this.customer);
    }
  }
};
</script>

<style scoped></style>

Это приложение. js:

require('./bootstrap');
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false
Vue.component('pagination', require('laravel-vue-pagination'));

new Vue({
  render: h => h(App),
}).$mount('#app')

может в этом проблема?

Of c вот ошибка типа

Свойство или метод «customers» не определены в экземпляре, но используются во время рендеринга

Приложение действительно работает так, но я хотел бы это исправить. Вот git для более чистого вида https://github.com/rade98/laravel

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...