Home > OS >  Is there a way to NOT refresh the Page after Updating the data? Laravel 8 and Vue
Is there a way to NOT refresh the Page after Updating the data? Laravel 8 and Vue

Time:03-20

How can I not refresh or reload the page after updating the data? I am using Modal to edit the data but the problem is the page still refresh after saving it, is there another way around to fix this concern?

<button  @click="edit(item)"><i ></i></button>

Modal:

<div  id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div  role="document">
                <div >
                <div >
                    <h5  id="exampleModalLabel">Employee Edit</h5>
                </div>
                <div >
                    <div >
                        <label>Name</label>
                        <input type="text"  v-model="formEdit.name">
                    </div>
                  ......

Script: (edit is used to show the data and update is used to update the data)

edit(item){
    const vm = this;
    vm.formEdit.name = item.name;
    vm.formEdit.address = item.address;
    vm.formEdit.position = item.position;
    this.selectedId = item.id;
    $('#editModal').modal('show');

},
update(){
    const vm = this;
    axios.put(`/employees/${vm.selectedId}`, this.formEdit)
    .then(function (response){
      alert('Employee Updated')
      location.reload();
    })
    .catch(function (error){
        console.log(error);
    });
}

This is for Laravel 8 and Vue

employees component:

props: ['employee'],
data() {
    return {
        employeeList: this.employee,
        form:{
            name: null,
            address: null,
            position: null
        },
        formEdit:{
            name: null,
            address: null,
            position: null
        },
        selectedId: null
    }
}

CodePudding user response:

during update remove

location.reload();

and add the below code

$('#editModal').modal('hide');

To display data follow the procedure, update data receive from response:

updateStudent(){
            axios.put('update_student',{
                id:this.id,
                name:this.editname,
                email:this.editemail,
                phone:this.editphone,
            })
             .then(response=>console.log(response));
             axios.get('all_students')
            .then(response => {
                this.data = response.data;
            });
        },

You can display the updated data like the below code:

<tr v-for="row in data"> 
  <th scope="row">1</th> 
  <td>{{ row.name }}</td> 
</tr>

CodePudding user response:

Please next time add all relevant code to let us know what are you trying to achieve.

First of all, please note that data provided from props should not be mutated because of an anti-pattern. Said that you have to create a deep copy within your component in order to change its content.

Assuming that you are working in just 1 component, where you have your table listing all employees, you can do something like this.

<template>
    <div>
        <table>
            <tr v-for="item in employeeList" :key="item.id">
                <td>name: {{ item.name }}</td>
                <td>address : {{ item.address  }}</td>
                <td>position : {{ item.position  }}</td>
                <td><button  @click="edit(item)"><i ></i></button></td>
            </tr>
        </table>

        <div  id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div  role="document">
                <div >
                  <div >
                      <h5  id="exampleModalLabel">Employee Edit</h5>
                  </div>
                  <div >
                      <div >
                          <label>Name</label>
                          <input type="text"  v-model="form.name">
                      </div>
                  </div>
                  <div >
                      <button  @click="update()">Save</button>
                  </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    props: {
        employee: Array
    },

    data: () => ({
        employeeList: [],
        form: {}
    }),

    mounted () {
        // Since changing a props is anti-pattern, we use a local data which can be manipulated
        this.employeeList = [...this.employee]
    },

    methods: {
      edit(item){
          // Assign the clicked item to form data
          this.form = item
          $('#editModal').modal('show')
      },

      update(){
          axios.put(`/employees/${this.form.id}`, this.form)
            .then(function (response){
                alert('Employee Updated') 
                // Find the employee index in employeeList array
                const updatedEmployee = response.data
                const index = this.employeeList.findIndex(x => x.id === updatedEmployee.id)
                // If employee is found, then proceed to update the array object by using ES6 spread operator
                if (index !== -1) {
                    this.employeeList = [...this.employeeList.slice(0, index), { ...updatedEmployee}, ...this.employeeList.slice(index   1)]
                }             
            })
            .catch(function (error){
                console.log(error)
            })
      }
    }
}
</script>

Code is self-explanatory, but just in case I will clarify a little bit:

  1. Because we can not mutate the props employee, we copy the array to local data by using the ES6 spread operator in mounted() hook.
  2. When you click the button to edit an employee, you assign the item to the form data. Now you have the form with all employee data to be shown/changed anywhere.
  3. Once success API response, since you are updating, you look for the array object and replace the whole array to avoid reactivity issues. In case you are adding a new one, you just can push it by doing this.employeeList.push(updatedEmployee)

EDIT: please note that the above code is a suggestion about how to work with a clean code. Anyway, right to your question, you can update your array in your axios response by doing

            .then(function (response){
                alert('Employee Updated') 
                // Find the employee index in employeeList array
                const updatedEmployee = response.data
                const index = this.employeeList.findIndex(x => x.id === updatedEmployee.id)
                // If employee is found, then proceed to update the array object by using ES6 spread operator
                if (index !== -1) {
                    this.employeeList = [...this.employeeList.slice(0, index), { ...updatedEmployee}, ...this.employeeList.slice(index   1)]
                }             
            })
            .catch(function (error){
                console.log(error)
            })
  • Related