【问题标题】:Map array inside computed property计算属性内的映射数组
【发布时间】:2025-12-11 19:05:01
【问题描述】:

所以我想看看如果有更好的方法来解决这个问题,我是否可以从社区获得一些指导:

所以我有以下vue.js 应用程序:

new Vue({
    name: 'o365-edit-modal-wrapper',
    el: '#o365-modal-edit-wrapper',
    data: function() {
        const default_apps = [
            {
                'post_title': 'Excel',
            }, {
                'post_title': 'Word',
            }, {
                'post_title': 'SharePoint',
        }];

        return {
            available_list: [],
            selected_list: default_apps.map(function(name, index) {
                return { name: name.post_title, order: index + 1, fixed: false };
            }),
        }
    },
    computed: {
        dragOptions() {
            // Pass in additional <draggable> options inside the return for both lists.
            return {
                tag: 'div',
                group: 'o365apps',
                disabled: !this.editable,
                ghostClass: "ghost",
            };
        },
    },
});

selected_list 返回以下项目:

有人告诉我,在数据返回中进行数组映射是不好的做法,而是在计算调用中进行映射 - 有人可以引导我朝着正确的方向前进,看看我的代码是否有意义?

我尝试定义一个空数组,如下所示:

return {
    available_list: [],
    selected_list:[],
}

& 然后在计算属性中,我尝试使用以下返回值访问它,但没有返回任何数据:

selected_list() {
  return this.default_apps.map(function(name, index) {
      return { name: name.post_title, order: index + 1, fixed: false };
  });
},

感谢所有帮助 - 非常感谢!

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    除了一些细节之外,您几乎都在那里:

    1. 可以将数据映射到data 中,只要将它们放在返回对象字面量data() { return { default_apps: [] } } 中即可。
    2. 一旦default_appsdata 的返回对象中,您可以使用this 关键字从计算属性访问其中的数据:this.default_apps.map()...
    
    new Vue({
        name: 'o365-edit-modal-wrapper',
        el: '#o365-modal-edit-wrapper',
        data: function() {
          return {
            default_apps: [
              { post_title: 'Excel' }, 
              { post_title: 'Word' },
              { post_title: 'SharePoint'}
            ],
            available_list: [],
          }
        },
      computed: {
          selected_list() {
            return this.default_apps.map(function(name, index) {
              return { name: name.post_title, order: index + 1, fixed: false };
            });
          },
          dragOptions() {
            // Pass in additional <draggable> options inside the return for both lists.
            return {
              tag: 'div',
              group: 'o365apps',
              disabled: !this.editable,
              ghostClass: "ghost",
            };
          },
        },
    });
    
    

    【讨论】:

    • 谢谢@Firmino!我是 vue 的新手,所以我在进步的同时也在学习,所以非常感谢 - 我现在将进行测试。
    • 跟上,你很快就会到达那里!
    • 我有一个问题 Firmino,所以它工作得很好,但是一旦我将项目拖到另一个数组中,它似乎变得未定义。您可能知道这背后的原因吗?
    • 能分享一下拖拽动作的逻辑吗?
    • 当然可以让我很快做出一个 jsfiddle。