Reputation: 13
I would like to select object from array in Vue.js :
On pageload, the selectTitle() method is called. I just want to select object (for example i=2) in my array 'titleList'. But for now I just get the Observer in return. I know it's about kind of scope or bind but I'm really new in vue (and js !) so someone could help me ?
Thanks !
var vm = new Vue({
el: '#titles',
data: {
titleList: [
{ title: 'Title1', details: 'details1', imgLocation:'', text: 'Lorem ipsum dolor sit amet.' },
{ title: 'Title2', details: 'details2', imgLocation:'', text: 'Lorem ipsum dolor sit amet.' },
{ title: 'Title3', details: 'details3', imgLocation:'', text: 'Lorem ipsum dolor sit amet.' },
{ title: 'Title4', details: 'details4', imgLocation:'', text: 'Lorem ipsum dolor sit amet.' },
{ title: 'Title5', details: 'details5', imgLocation:'', text: 'Lorem ipsum dolor sit amet.' }
],
},
mounted: function () {
this.setTimer();
this.selectTitle();
},
methods: {
selectTitle() {
i = 2;
let currentTitle = this.titleList[i];
console.log(i, currentTitle);
return currentTitle;
},
Upvotes: 0
Views: 2417
Reputation: 8435
That's perfectly normal and exactly what you want to happen. Vue wraps every object into an observable automatically for you, so that when your data changes, all data-bindings in view update automatically without you having to do anything. Don't worry about it, this works as a proxy, you can manipulate this object just normally. For example:
currentTitle.title = 'Changed title'
Will update the correct attribute and if you have a reference in your view, even update your view automatically without you having to worry about anything. That's the great thing about Vue.
Here's a codepen example taking your code a bit further, hope that helps understanding: Codepen Example
Upvotes: 1