Search code examples
javascriptvue.jsdata-binding

Vue JS: How to prevent Input updating itself on livedata?


I'm passing data to Modal for editing. The problem is whenever my products data is updated (Every 5s via fetchData), input field in modal also changed. How to prevent it?

Below is a simplified version of my code.

<div id="app">
  <div class="modal" id="modal1">
    <form method="post">
      <input type="text" :value="passedData.category" />
      <input type="text" :value="passedData.rating" />
      <input type="text" :value="passedData.price" />
      <input type="text" :value="passedData.stock" />
      <button>Submit</button>
    </form>
  </div>

  <table>
    <tr v-for="item in items">
      <td>{{ item.sku }}</td>
      <td>{{ item.stock }}</td>
      <td><button @click="openModal('modal1', item)">Edit</button></td>
    </tr>
  </table>
  
</div>

<script>
  const app = Vue.createApp({
    data() {
      return {
        items: [],
        passedData: [],
      };
    },
    mounted() {
      this.fetchData();
      setInterval(this.fetchData, 5000);
    },
    methods: {
      async fetchData() {
        const response = await fetch("https://dummyjson.com/products");
        const data = await response.json();
        this.items = data.products;
      },
      openModal(idModal, item) {
        this.passedData = Object.assign({}, item);
      },
    },
  });

  app.mount("#app");
</script>

Solution

  • As per this documentation - in your <input>'s, use v-model instead of :value - i.e.

    <div class="modal" id="modal1">
        <form method="post">
            <input type="text" v-model="passedData.category" />
            <input type="text" v-model="passedData.rating" />
            <input type="text" v-model="passedData.price" />
            <input type="text" v-model="passedData.stock" />
            <button>Submit</button>
        </form>
    </div>