0

I am retrieving an object of objects, for each object I am making a list of text inputs to edit their values. My problem is that the value of the input is not changing so it only submits with the starting value, how can I make the input value dynamic?

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

...

methods: {
    updateVariable(id, value) {
        axios.post('/destination', {
                params: {
                    id: id,
                    value: value
                }
            })
                .then((response) => {
                    console.log(response);
                })
                .catch((error) => {
                    console.log(error);
                })
    }
}

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That works perfectly... I thought :value was just the short hand of v-model lol. Thank you.
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/[email protected]/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>

1 Comment

That works perfectly... I thought :value was just the short hand of v-model lol. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.