How to set data properties to value returned from Vuex getter

Viewed 19345

I have a Vue component that will display data depending on what the user previously clicked on in a previous component. When they originally click, I set the 'current' index. Then when they get to the next page, I have a getter that will look in the data array and return the 'current' data.

The component they are redirected to is a form that they can edit. I would like to be able to have the 'current' data be pre-populated. NOT as a placeholder but as the actual value so that they can edit it directly.

The issue is I don't know how to set the values returned from the getter to the data function values so that they can be bound with v-model.

HTML

<input type="text" class="form-control" id="nickname1" v-model="name" name="name">
<input type="text" class="form-control" id="address1" placeholder="" v-model="address" name="address" > 
<input type="text" class="form-control" id="city1" placeholder="" v-model="city" name="city" > 

VUE

data: function() {
    return {
        name: this.currentArea.title,
        address: this.currentArea.address,
        city: this.currentArea.city,
        state: this.currentArea.state
    }
},
computed: {
    currentArea() { return this.$store.getters.currentArea }
}

*this.currentArea.title and currentArea.title do not work.

*if I bind the placeholder, the data displays correctly, so the getter function is returning currentArea correctly

2 Answers

@thanksd: thank you for your answer. I am working on a scenario where the state is stored in vuex, temporarily sent incomplete to the component and then updated through a fetch. And it should be editable in a form.

My solution was to export part of the state with a getter in vuex:

getters: {
  getItemDetail: (state, getters) => (id) => {
    let item = state.openedItems.items.find(i => i.id === id);
    return item ? item.data : null;
  }
}

using it in the component by combining data, computed and watch properties (and deep cloning the object with the help of lodash):

data () {
  return {
    itemDetail: null
  };
},
computed: {
  itemData () {
    return this.$store.getters.getItemDetail(this.item.id);
  }
},
watch: {
  itemData (n, o) {
    this.itemDetail = _.cloneDeep(n);
  }
}

Finally I bind the input to "itemDetail" (using an elemen switch, in my example):

<el-switch v-model="itemDetail.property"></el-switch>

To me (but I am quite new to Vue), it seems a good and working compromise.

Related