0๐
You do not need to use the watch function since you are using two way
bind. You also should not use v-model for the total field since you are not
actually entering any value in there. This is why computed properties
are available.
import { computed } from @vue/composition-api
since you are using composition api and then it should update normally
To use:
setup(){
const total = computed(() => {
return data.value.quantity * data.value.price
})
return { total }
}
Do not forget to return the computed property. with this you will be able to make use of total in your component by just calling total
and it should update automatically when the other entries are changed.
If you would like to compress your computed property because they match you can return an object
setup(){
const properties = computed(() => {
return {
total: data.value.quantity * data.value.price
margin: other_function()
}
})
return { properties }
}
You could chose to call the function first and attach the result to a key as its value instead of just calling it within the object(as its value) like i specified above
With this you will be able to work with properties
computed property as an object all around you components
0๐
You should use watch
property like this.
new Vue({
el: "#app",
data: {
data: {
quantity: 4,
price: 10,
total: 40
},
},
watch: {
'data.quantity': function(val) {
console.log(val);
this.data.total = this.data.price * val;
},
'data.price': function(val) {
console.log(val);
this.data.total = val * this.data.quantity;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input v-model.number="data.quantity" type="text" class="pdg-input" />
<input v-model.number="data.price" type="text" class="pdg-input" />
<input v-model="data.total" type="text" readonly class="pdg-input" />
</div>