Vue.js交换数组项

11

在我的 vue.js 应用程序中,我正在尝试像这样交换 2 个论坛行:

export default {
        data() {
            return {
                forums: []
            }
        },

        methods: {
            increment(forum, index) {
                ForumService.increment(forum)
                    .then(() => {
                        let b = this.forums[index];
                        this.forums[index] = this.forums[index++];
                        this.forums[index++] = b;
                    });
            }
        }
    }

但是什么也没有发生?我在这里做错了什么吗?

1个回答

21

虽然 @dfsq 谈到使用 index++ 是正确的,但是由于 Vue 无法观察到原生数组的变化,因此不能直接对其进行修改。你必须使用突变方法来改变它们。

尝试这个:

.then(() => {
  let rows = [this.forums[index], this.forums[index + 1]];
  this.forums.splice(index, 2, rows[1], rows[0] );
});

我还没有测试过,等我有时间时会进行编辑。


这个关于splice的说法是正确的。然而,this.forums.splice(index, 2, this.forums[index + 1], this.forums[index]);就足够了。 - dfsq
@dfsq 是的,只是个人偏好,用于保存数值。 - Justin MacArthur
不,我的意思是你的代码不能使用数组作为第三个参数。应该是 this.forums.splice(index, 2, rows[1], rows[0] ); - dfsq
啊,你说得对。谢谢你注意到了这个问题,我回家后会进行更改。 - Justin MacArthur
谢谢 - 真的很喜欢这种方法,完美地运作了 :) - Darragh Enright

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接