【问题标题】:Moving items between arrays in vue.js在 vue.js 中的数组之间移动项目
【发布时间】:2016-06-21 18:45:36
【问题描述】:

我有两个数组,每个数组都有自定义组件。

List a 是一个搜索结果。列表 b 是所选项目的列表。

每个组件都有一个模板,用于呈现数组中的项目。

所以...我遇到的麻烦是,一旦我的列表在列表 a 中,我想单击一个链接并将其添加到列表 b。但是当我尝试添加该项目时,我被告知Cannot read property 'push' of undefined

这是我的整个 Vue。我做错了什么?

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']

        }  
    }
});

【问题讨论】:

    标签: javascript arrays vue.js


    【解决方案1】:

    您应该将 listAlistB 初始化为空数组,而不是像这样的空字符串

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

    这将允许您在listaitem 组件中使用this.listB.push(listaitem); 而不会引发错误

    【讨论】:

    • 你是对的!另一个缺失是我需要获取父级才能将其添加到另一个数组中。所以... this.$parent.listb 不是 this.listb
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 2014-12-06
    • 2015-12-18
    • 1970-01-01
    相关资源
    最近更新 更多