我将 photoswipe (v5) 添加到这样的组件中:
mounted () {
if (!document.getElementById('psw')) {
const script = document.createElement('script')
script.id = 'psw'
script.type = 'module'
script.innerHTML = `
import PhotoSwipeLightbox from '/js/photoswipe/photoswipe-lightbox.esm.min.js';
const lightbox = new PhotoSwipeLightbox({
gallerySelector: '#gallery--productimages',
childSelector: 'a',
pswpModule: '/js/photoswipe/photoswipe.esm.min.js'
});
lightbox.init();
`
document.head.appendChild(script)
}
},
photoswipe 文件位于静态文件夹中。 script 标签已添加到 DOM,但第一次加载页面时(来自内部路由链接和直接服务器调用),photoswipe 不会执行。当我通过内部链接返回并再次打开页面或刷新页面时,它可以工作。 我只想在这个组件中使用 photoswipe。我怎样才能使它也适用于首页加载?
最佳答案
我认为这不是在应用程序中注入(inject)脚本的好方法。 我通常这样加载外部包:
首先,我在 plugins
文件夹下创建 PhotoSwipe.js
:
import PhotoSwipe from '/js/photoswipe/photoswipe.esm.min.js'
import PhotoSwipeLightbox from '/js/photoswipe/photoswipe-lightbox.esm.min.js'
export default (context, inject) => {
inject('PhotoSwipe', PhotoSwipe)
inject('PhotoSwipeLightbox', PhotoSwipeLightbox)
}
然后我将其加载到 nuxt.config.js
内的插件属性中:
plugins: [
{ src: '~/plugins/PhotoSwipe', mode: 'client' }
]
然后您可以通过以下方式在任何页面或组件中使用它:
data () {
return {
lightbox: {}
}
},
mounted () {
this.loadPhotoSwipeLightBox()
},
beforeDestroy () { // added
this.closeLightBox()
},
methods: {
loadPhotoSwipeLightBox () {
const options = {
// define the images to load in lightbox
dataSource: [
{
src: 'https://source.unsplash.com/Volo9FYUAzU/1620x1080',
w: 1600,
h: 1600,
alt: 'test image 1'
}
],
pswpModule: this.$Photoswipe
}
this.lightbox = new this.$PhotoswipeLightbox(options)
this.lightbox.init()
/* const lightbox = new this.$PhotoSwipeLightbox({
gallerySelector: '#gallery--productimages',
childSelector: 'a',
pswpModule: this.$PhotoSwipe
});
lightbox.init();
*/
},
openLightBox () { // this method should be called onClick on the thumbnailimage
this.lightbox.loadAndOpen(0) // exchange 0 with the dynamic index of the thumbnail => to do
},
closeLightBox () {
if (this.lightbox) {
this.lightbox.destroy()
}
}
}
编辑:在 pswpModule 中使用注入(inject)的 this.$PhotoSwipe
而不是 URL。
编辑:添加 closeLightBox() 来关闭灯箱,也可以通过单击浏览器后退按钮,使用 dataSource-Array 将图像加载到灯箱中
关于nuxt.js - 努克斯 : added client side js is not executed at first page load,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68558946/