【问题标题】:Vuejs : How to make a computed property which observe a list of items?Vuejs:如何创建一个观察项目列表的计算属性?
【发布时间】:2019-11-07 10:15:52
【问题描述】:

我想在我的应用程序中同步两个数组中的数据。我正在使用 vue.js。

我的第一个数组是这样的:

    var testLayout = [
        {"x":0,"y":0,"w":2,"h":2,"i":"0"},
        {"x":2,"y":0,"w":2,"h":4,"i":"1"}
    ];

第二个包含项目对象是这样的:

    var items = [
        item {
            //other properties
            Position = {
                x,
                y,
                Width,
                Height,
                MinWidth,
                MaxWidth,
                MinHeight,
                MaxHeight
            }
        },
        ....
    ]

我希望第一个数组中的属性对第二个数组的变化做出反应,反之亦然。 我需要像这样同步我的数据:testLayout[...].myAnonymousObject.x <=> items[...].item.Position.x

如何创建计算属性或我可以用来实现此目的的东西?我无法更改这两个数组/对象的结构,但我需要让它们更新每个数组/对象的变化大大地。

我尝试在我的 vue 实例中执行此操作:

computed: {
            layout: {
                get: function () {
                    let allPositions = [];
                for (var item of items) {
                    allPositions.push(
                        {
                            x: item .Position.x,
                            y: item .Position.y,
                            h: item .Position.Height,
                            w: item .Position.Width,
                            i: item .Id
                            //do not set here min/maxW and min/maxH
                        }
                    );
                }
                return allPositions;
                },
                set: function () {
                    ???
                }
            }

        },

但这不起作用,我不知道如何真正将这些属性绑定在一起。你知道怎么做吗 ?我使用计算属性来做到这一点是对的吗?

【问题讨论】:

    标签: arrays vuejs2 computed-properties


    【解决方案1】:

    我在实际项目中遇到了与此类似的事情。 我已经搜索过了,有一个选项可以深入观看,是数组数组、对象数组、数组对象等的最佳选择...

    应该是这样的:

    watch: {
         <variableName>: { // should be the name of the variable you want to watch
            // if you want, this handler() allows 2 params like (newValue, oldValue) to compare something if you want.
            handler() {
                // do your logic
                // call a function with the logic
            },
            deep: true
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-19
      • 2017-04-25
      • 2016-12-28
      • 2021-03-07
      • 2017-09-02
      • 2016-04-22
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多