1

I have a vue instance:

    var vue = new Vue({
      el: '#vue-wrapper',
      data: {
        items: [],
        selectedItem: ''
    })

I initialize items with data coming from my phoenix server like this:

vue.items = <%= raw(@stories) %>

When my page has loaded, i want to select the first item as starting item:

vue.selectedItem = vue.items[0]

I have an input field in my html that is bind to title property of my object

<input type="text" v-model="selectedItem.title"></input>

Databinding works fine, problem is that items[0] is updating together with selectedItem, and i don't want it. What i've tried:

var x = vue.items[0];
vue.selectedItem = X;

still binding,

var x = <%= raw(@stories) %>
vue.items = x[0]
vue.selectedItem = x[0]

still binding, and:

vue.selectedItem = Object.assign({}, vue.items[0]);

and still there's binding between objects. How can i get 2 way databinding only for selectedItem?

Razinar
  • 727
  • 3
  • 13
  • 21
  • Yes because it's an editor. So it should be editable – Razinar Feb 16 '18 at 18:08
  • 1
    Try `vue.selectedItem = { ...vue.items[0] };`, or `vue.selectedItem = JSON.parse(JSON.stringify(vue.items[0]));` or use something like [lodash#cloneDeep](https://lodash.com/docs/4.17.4#cloneDeep), you need to clone the object, right now you have a reference to the original object. – Ricky Ruiz Feb 16 '18 at 20:15
  • Are you looking to [initialize the value from the HTML](https://stackoverflow.com/a/45215757/392102)? – Roy J Feb 17 '18 at 02:46

1 Answers1

2

I reproduced your case in jsfiddle and Object.assign is working very well.

var vue = new Vue({
      el: '#vue-wrapper',
      data: {
          items: [{
            title: 'title-item'
          }],
          selectedItem: ''
      }
    })

    vue.selectedItem = Object.assign({}, vue.items[0])

https://jsfiddle.net/50wL7mdz/107302/

Tomasz Kostuch
  • 239
  • 1
  • 14
  • I see. I've already tried it but the binding is still real. I need to check my code to see if i've made another binding somewhere else. Thank you Tomasz – Razinar Feb 19 '18 at 07:48