Рубрики
Laravel+Vue3 project Vue.js Vue компоненты Laravel

Vue Создать запись в БД

Форма создания записи

отправка данных в дочерний компонент app через emit
resources\js\components\Row\Create\RowCreate.vue

<template>
<form @submit.prevent>
<h4>Создание Записи</h4>

<input type="text" v-model="row.name" class="input" placeholder="Название">
<input type="text" v-model="row.description" class="input" placeholder="Описание">
<button class="btn" @click="createRow">Создать</button>

</form>
</template>

<script>
export default{
data:function(){return {
row:{
    name:'',
    description:'',
}
}
},
methods:{
createRow(){
 //this.post.id=Date.now();
 this.$emit('create',this.row,'second param','3 param');
 this.row={name:'',description:''}
} 
}
}
</script>

<style>
.input {
 width:100%;
 border:1px solid teal;
 padding: 10px 15px; 
 margin-top: 15px;
}
.form{
 display:flex;
 flex-direction:column;
}
.btn{
 margin-top: 15px;
 align-self: flex-end;
 padding: 1opx 15px;
 background:none;
 color:teal;
 border: 1px solid teal;
}
</style>

Главный компонент
resources\js\components\MyApp.vue

<template>
<div class="app">
<my-button @click.native="showDialog" style="margin: 15px 0;">Создать запись</my-button>
<!--диалоговое окно создания записи-->
<my-dialog v-model:show="dialogVisible">
<row-create @create="createRow"/>
</my-dialog>

<h1>Страница с записями</h1>

<row-list v-if="!isRowsLoading" :rows="rows" @remove="removeRow"/>
<div v-else>Идет загрузка...</div>
</div>
</template>

<script>
export default{
data: function () {
return {
rows:[],
dialogVisible:false,
isRowsLoading:false, 
}
},
methods:{
 createRow(row,second,third){
  this.rows.push(row);
  
  axios.post('/api/create', row)
  .then((response) => {console.log(response);})
  .catch(function (resp){
   console.log(resp);
   alert("Не удалось записать в БД");
  });
  this.dialogVisible = false;
 },
 removeRow(row) {
  this.rows = this.rows.filter(p => p.id !== row.id)
 },
 showDialog(){
  this.dialogVisible = true;
 },
 async fetchRows(){
  try{
   this.isRowsLoading = true;

   setTimeout(async()=> {
       const response = await fetch('/api/all');
       
       if (response.status === 200){
           const result = await response.json();
           this.rows = result;
           console.log(result);
        }
        this.isRowsLoading = false;
    },1000)  
  } catch(e){
   alert('ошибка')
  }
 }
},
mounted(){
  this.fetchRows();
 },
}
</script>

<style>
* {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
.app{
 padding: 20px;
}
</style>

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *