[Vuejs]-Using the new value of a dynamic vue input

0👍

Use v-model, :value won’t track the change

// Fake axios to debug with
const axios = {
  post(ep = "", data) {
    console.log(`would send \n${JSON.stringify(data)}\nto ${ep}`);
    return Promise.resolve("OK");
  }
};

const app = new Vue({
  el: "#app",
  data() {
    return {
      variables: {
        foo: {
          id: "foo",
          value: "bar"
        },
        fizz: {
          id: "fizz",
          value: "buzz"
        }
      }
    };
  },
  methods: {
    updateVariable(id, value) {
      axios.post('/destination', {
          params: {
            id: id,
            value: value
          }
        })
        .then((response) => {
          console.log(response);
        })
        .catch((error) => {
          console.log(error);
        })
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.min.js"></script>
<div id="app">
  <ul>
    <li v-for="variable in variables">
      <input type="text" v-model="variable.value" />
      <button @click="updateVariable(variable.id, variable.value)">Update</button>
    </li>
  </ul>
</div>

3👍

You are just giving an initial value to each input, but you’re not binding it to any reactive data attribute.

Use the v-model directive to use input bindings and apply Vue’s reactivity to the input:

<ul>
    <li v-for="variable in variables">
        <input type="text" v-model="variable.value" />
        <button @click="updateVariable(variable.id, variable.value)">Update</button>
    </li>
</ul>

Please note that the variables array must be declared inside your component’s data object for this to work properly.

👤mtflud

Leave a comment