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?

3
  • Yes because it's an editor. So it should be editable Commented Feb 16, 2018 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, you need to clone the object, right now you have a reference to the original object. Commented Feb 16, 2018 at 20:15
  • Are you looking to initialize the value from the HTML? Commented Feb 17, 2018 at 2:46

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.