clairechang0609 / hexo-board

0 stars 0 forks source link

Nuxt.js 套件應用:Masonry 打造瀑布流版面 - Claire's Notes #3

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

Nuxt.js 套件應用:Masonry 打造瀑布流版面 - Claire's Notes

瀑布流版面能夠快速的幫我們達成 RWD 區塊排版,本篇說明如何在 Nuxt.js 專案利用 masonry-layout 套件打造瀑布流版面

https://clairechang.tw/2022/12/23/nuxt/nuxt-masonry/

AAAAAAAAAdai commented 1 year ago

Can you provide a tutorial on how to run in Nuxt 3?

clairechang0609 commented 1 year ago

Can you provide a tutorial on how to run in Nuxt 3?

If you are using composition API, maybe you can try to define Masonry in the composable directory like this

// composables/useMasonry.js
import Masonry from 'masonry-layout';
export default function() {
    return Masonry;
}

then use composable in pages

<script>
export default {
    setup() {
       const Masonry = useMasonry();
       let masonry;
       onMounted(() => {
           masonry = new Masonry(element, optoins)
       });
    }
}
</script>
AAAAAAAAAdai commented 1 year ago

Thanks a lot for your response. I ran into an error that said "window is not defined". So I made some changes to the code like this:

// plugins/masonry.client.js
import Masonry from 'masonry-layout'
export default defineNuxtPlugin(() => {
      return {
            provide: {
                  masonry:(element, optoins) => {
                        return new Masonry(element, optoins);
                  }
            }
      }
});

in pages

const { $masonry } = useNuxtApp()
let masonry;
onMounted(() => {
      let el = document.querySelector('.list');
      masonry = $masonry(el, {
            columnWidth: 240,
            gutter: 20,
            itemSelector: '.item',
            transitionDuration: '0.3s',
            horizontalOrder: true
      });
});
AAAAAAAAAdai commented 1 year ago

and if u need push , tyr👇

const load = () => {
      // nuew data
      data.value.push(...newData.value)
      nextTick(() => {
            let item = document.querySelectorAll('.item:not([style*="position: absolute"])');
            msnry.appended( item )
      })
}
clairechang0609 commented 1 year ago

You're right. Since you're using SSR mode, the 'Masonry' must be defined in client-side only plugins, or else we'll get the 'window is not defined' error.