Reputation: 12174
(Note: I not am not asking about how to use watch
).
I have this form template and want to bind it to some variables, for example objectvalue3
, that are tracked in a Vuex store (note: different forms may be present on one page, so props.formname
tells the form where to look).
<template>
<div>
Tracking formname_:{{formname_}}:
<form method="post" autocomplete="off">
<input type="text" name="objectvalue3" :value="objectvalue3" />
<input type="submit" class="btn btn-primary btn-success" value="Track" @click.prevent="write">
</form>
</div>
</template>
....
props: {
formname: {
type: String,
default: "main"
}
},
Tracking it in data
does not work - i.e. the form does not get updated - it just keeps the value the vuex was initialized to :
data: function() {
return {
formname_: this.formname
,objectvalue3: this.$store.state.tracker[this.formname].objectvalue3
},
But using computed
works.
computed: {
objectvalue3: function() {
return this.$store.state.tracker[this.formname].objectvalue3
}
I know I have to use computed
when I need to do calculations. But there is not real calculation going on here. Unless, could it be the hash lookup via this.formname
which tells the form which tracker
attribute to look at that is causing a straight data
to fail? Is this specific to vuex?
Upvotes: 7
Views: 7856
Reputation: 14982
Try this instead:
data: function() {
return {
formname_: this.formname,
tracker: this.$store.state.tracker[this.formname]
},
Then:
<input type="text" name="objectvalue3" :value="tracker.objectvalue3" />
This should work because the data's tracker
object is pointing to the one in the store, then whenever the value changes there, it'll also change in the tracker
object.
computed
works because it listens to changes in the variables used within it, while data doesn't because it applies the first value when executed and doesn't track changes.
Upvotes: 8