首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >nuxt:添加的客户端js不会在第一个页面加载时执行。

nuxt:添加的客户端js不会在第一个页面加载时执行。
EN

Stack Overflow用户
提问于 2021-07-28 10:45:08
回答 2查看 876关注 0票数 2

我在这样的组件中添加了光子擦除器(v5):

代码语言:javascript
运行
复制
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中,但是当第一次加载页面时(从内部路由链接和直接服务器调用),光子擦除不会执行。当我通过内部链接重新打开页面,或者刷新页面时,它就能工作了。我只想在这个组件中使用光擦片。我如何使它也工作在第一页加载?

EN

Stack Overflow用户

回答已采纳

发布于 2021-07-28 14:19:02

我不认为这是一个很好的方式注入脚本到您的应用程序。我通常以这种方式加载外部包:

首先,我在PhotoSwipe.js文件夹下创建plugins

代码语言:javascript
运行
复制
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属性中加载它。

代码语言:javascript
运行
复制
plugins: [
  { src: '~/plugins/PhotoSwipe', mode: 'client' }
]

然后您可以在任何页面或组件中以这种方式使用它:

代码语言:javascript
运行
复制
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中的图像

票数 3
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68558946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档