Dave Merwin
Dave Merwin

Reputation: 1412

Moving items between arrays in vue.js

I have two arrays with custom components in each.

List a is a search result. List b is a list of selected items.

Each component has a template that renders the item in the array.

So... the trouble I'm having is, once I have my list in list a, i want to click a link and have it add to list b. But when I try to add the item, I'm being told that Cannot read property 'push' of undefined

Here's my entire Vue. What am I doing wrong?

new Vue({

    el: '#search',
    data: {
        query: '',
        listA: '',
        listB: ''
    },
    methods: {

        search: function(event) {

            if (this.query != "") {
                this.$http({url: '/list-a?search=' + this.query, method: 'GET'}).then(function(response) {
                    this.listA = response.data
                });
            };

            event.preventDefault();
        }

    },
    components: {
        listaitem: {
            template: '#listaitem-template',
            props: ['lista-item'],
            methods: {
                selected: function(listaitem) {
                    // When clicked, this will add this listaitem to listB
                    this.listB.push(listaitem);
                }
            }
        },

        listbitem: {
            template: '#listbitem-template',
            props: ['listbitem']

        }  
    }
});

Upvotes: 0

Views: 1711

Answers (1)

Ogie
Ogie

Reputation: 1324

You should initialize listA and listB as empty arrays instead of empty strings like

data: {
        query: '',
        listA: [],
        listB: []
}

This will allow you use this.listB.push(listaitem); in the listaitem component without throwing an error

Upvotes: 1

Related Questions