首页 > 解决方案 > 必须在页面上加载图像时,机车滚动无法与 Vue.js 一起使用

问题描述

我正在尝试实现 Locomotive-Scroll.js 并在我的页面上加载图像时遇到问题。滚动效果在没有图像的情况下工作,但在加载图像时会中断。我认为挂载功能会阻止加载滚动效果,直到所有 dom 元素都被加载,所以我不确定我从这里去哪里。这是我正在使用的 JS:

<script>
import locomotiveScroll from "locomotive-scroll";
import $ from 'jquery'

export default {
  name: "locoScroll",
  props: {
    msg: String
  },
  data() {
    return {
      scrollIns: null,
  },
  mounted() {
    this.loadLanding();
    const _self = this;
    this.$nextTick(function() {
      _self.initLocoScroll(); 
    });
  },
  methods: {
    initLocoScroll() {
      const _self = this;
      this.scroll = new locomotiveScroll({
        el: _self.$refs['scrollSections'],
        smooth: true,
        smoothMobile: true,
        getDirection: true,
        initClass: true
      });
      this.scroll.update();
    },
      loadLanding: function () {
          //image & jobTitle fade in
          var elements = ['nav-links-top','rocks-image','job-title-container'];

          for (let i = 0; i < elements.length; i++) {
              var thisElement = $("." + elements[i]); //Get the current element based on class
              fadeInElement(thisElement, i);          //Call our "Fade in" function
          }
          function fadeInElement(elem, time) {      //Fade-in function that takes the element to fade-in, and the time it should wait
              setTimeout(function() {
                  elem.css('opacity', 1);
              }, 1650 * time + 500);                        //Set the time it should wait
          }
      },
  }
};

</script>

标签: javascripthtmlvue.jsscrolluiscrollview

解决方案


也许这会有所帮助。我在 Nuxt 中使用 Vuejs,我遇到了类似的问题。

你需要在dom加载后触发机车update()。

我正在使用graphql从api中提取数据,所以我有动态数据,我必须等待机车才能正确计算页面高度。

Graphql apollo 有一个方便的加载参数,它可以是真或假。

我的解决方案是创建一个承诺,检查是否使用该参数加载了数据,然后触发 locomotive.update() 重新渲染页面高度。

mounted() {
    this.pageLoad();
  },

方法:

pageLoad() {
      return new Promise((resolve, reject) => {
        console.log("loading...");
        setInterval(() => {
          if (!this.$apollo.queries.projects.loading) {
            resolve("data fetched");
          }
        }, 100);
      })
        .then((res) => {
          console.log("loaded!", res);
          this.filteredProjects = this.projects.nodes;
          this.$refs.scroller.locomotive.update();
          this.$refs.scroller.locomotive.scroll.reinitScrollBar();
          console.log("loco updated");
        })
        .catch((err) => {
          console.error("error: ", err);
        });
    },

一旦您可以访问机车实例,您就可以告诉它进行更新。

希望在某种程度上有所帮助。


推荐阅读