Reputation: 3
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);
})
}
}
Upvotes: 0
Views: 8496
Reputation: 866
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.
Upvotes: 3
Reputation: 26867
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>
Upvotes: 0