woto
woto

Reputation: 3077

How to edit object like an array collection

Hi seems it's a not best practice to iterate and edit object (not array). But is there a best way to to it as easy as it could be done with array of objects?

https://jsfiddle.net/woto/q9zqefq0/11/

new Vue({
  el: '#app',
  data: {
    object1: {
      'first': 'second'
    },
    object2: [
      {'key': 'first', 'value': 'second' }
    ]
}})

--

<script src="https://unpkg.com/vue"></script>

<div id="app">

  <!-- Is there a way to make it work? -->
  <!-- `k` value of object is not reactive(?) -->

  <div v-for="(v, k) in object1">
    <p> {{ k }} | {{ v }} </p>
    <input type="text" class="form-control" v-model="k">
    <input type="text" class="form-control" v-model="object1[k]">
  </div>

  <br />

  <!-- This works fine like a charm -->

  <div v-for="item in object2">
    <p> {{ item }} </p>
    <input type="text" class="form-control" v-model="item.key">
    <input type="text" class="form-control" v-model="item.value">
  </div>

</div>

Upvotes: 1

Views: 100

Answers (2)

thanksd
thanksd

Reputation: 55644

This is a very silly thing to do, but if you really want to bind an object's property name to an input, you could do something like this:

new Vue({
  el: '#app',
  data: {
    object1: {
      'first': 'second'
    },
    object2: [
      {'key': 'first', 'value': 'second' }
    ]
  },
  methods: {
    updateObject(e, old, prop) {
      let val = this[prop][old];
      this.$delete(this[prop], old);
      this.$set(this[prop], e.srcElement.value, val);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>

<div id="app">

  <div v-for="(v, k) in object1">
    <p> {{ k }} | {{ v }} </p>
    <input type="text" class="form-control" :value="k" @input="updateObject($event, k, 'object1')">
    <input type="text" class="form-control" v-model="object1[k]">
  </div>
  
  <br />
  
  <div v-for="item in object2">
    <p> {{ item }} </p>
    <input type="text" class="form-control" v-model="item.key">
    <input type="text" class="form-control" v-model="item.value">
  </div>

</div>

Upvotes: 1

acdcjunior
acdcjunior

Reputation: 135772

The problem with the first is that when you edit

<input type="text" class="form-control" v-model="k">

being k the key, you are simply editing k the string.

It does not reflect in the original object because that's not a reference to the name of the property. It is mere a string (that was extracted from the name of the property).

Upvotes: 2

Related Questions