[Vuejs]-How to update Masonry on Vue.js 3 updated() lifecycle hook?

0👍

To cache a reference the resulting Masonry instance, just assign it to a property (you don’t need reactivity on this instance, so attaching a property is fine):

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

However, you’ll notice that the this._masonry.layout() call does not actually re-layout the masonry items (likely due to some limitation of the library). The only workaround I see is to recreate the Masonry instance, and then you no longer need to cache a reference to it:

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

demo

Leave a comment