我在这样的组件中添加了光子擦除器(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)
}
},
光擦除文件位于静态文件夹中。脚本标记被添加到DOM中,但是当第一次加载页面时(从内部路由链接和直接服务器调用),光子擦除不会执行。当我通过内部链接重新打开页面,或者刷新页面时,它就能工作了。我只想在这个组件中使用光擦片。我如何使它也工作在第一页加载?
发布于 2021-07-28 14:19:02
我不认为这是一个很好的方式注入脚本到您的应用程序。我通常以这种方式加载外部包:
首先,我在PhotoSwipe.js
文件夹下创建plugins
:
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属性中加载它。
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中使用注入的this.$PhotoSwipe
而不是url。编辑:添加closeLightBox()以关闭Lightbox,方法是单击浏览器后退按钮,使用dataSource获取加载到lightbox中的图像
https://stackoverflow.com/questions/68558946
复制相似问题