【问题标题】:How to update Masonry on Vue.js 3 updated() lifecycle hook?如何在 Vue.js 3 updated() 生命周期挂钩上更新 Masonry?
【发布时间】:2022-02-04 04:18:44
【问题描述】:

我有一个关于 Masonry 布局更新的问题。如何在 Vue.js(版本 3)生命周期钩子“updated()”中触发它?

我有一个类似于以下代码的卡片网格视图(在此处使用 Bootstrap 5),但在更新 Masonry 布局时遇到困难,例如一张卡片改变了它的大小。我知道我可以使用 layout() see documentation 但我不知道如何在我的示例中调用它。

所以我的主要问题是,当在 mount() 函数中初始化时,我不知道如何使我的 Masonry 对象在更新的函数中可访问。我该怎么做?

<template>
  <div
    class="row justify-content-left"
    data-masonry='{"percentPosition": true }'
  >
    <div class="col-md-6 col-lg-4 col-xxl-3 mb-4 card-col">
      <Card 1 />
    </div>
    <div class="col-md-6 col-lg-4 col-xxl-3 mb-4 card-col">
      <Card 2 />
    </div>
    <div class="col-md-6 col-lg-4 col-xxl-3 mb-4 card-col">
      <Card 3 />
    </div>
    <div class="col-md-6 col-lg-4 col-xxl-3 mb-4 card-col">
      <Card 4 />
    </div>
  </div>
</template>

<script>
[imports ...]

export default {
  name: "ComponentName",
  components: {
    [components ...],
  },
  mounted: function () {
    // initialize masonry
    this.$nextTick(function () {
      var row = document.querySelector("[data-masonry]");
      new Masonry(row, {
        // options
        percentPosition: true,
      });
    });
  },
  updated: function() {
    //-->how to call the relayout of Masonry here?
  }
};
</script>

【问题讨论】:

  • 您不保存 Masonry 实例,因此您以后无法访问它。对任何第三方库执行相反的操作是个好主意,而不仅仅是砌体
  • 您好埃斯图斯,感谢您的回答!对于这种特殊情况,在 Vue.js 中执行此操作的最佳方法是什么?

标签: vue.js vuejs3 bootstrap-5 grid-layout masonry


【解决方案1】:

要缓存引用生成的Masonry 实例,只需将其分配给一个属性(您不需要对该实例进行反应,因此附加一个属性就可以了):

export default {
  mounted() {
    this._masonry = new Masonry(this.$refs.masonry, ⋯)
  },
  updated() {
    this._masonry.layout()
  }
}

但是,您会注意到 this._masonry.layout() 调用实际上并没有重新布局砌体项目(可能是由于库的某些限制)。我看到的唯一解决方法是重新创建 Masonry 实例,然后您不再需要缓存对它的引用:

export default {
  mounted() {
    this.$nextTick(() => this.layout())
  },
  updated() {
    this.layout()
  },
  methods: {
    layout() {
      new Masonry(this.$refs.masonry, ⋯)
    }
  }
}

demo

【讨论】:

    猜你喜欢
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 2020-03-20
    • 1970-01-01
    • 2016-09-28
    • 2021-01-25
    相关资源
    最近更新 更多