简体   繁体   中英

How to get object from array in vue.js

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;
        },

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM