简体   繁体   English

Nuxt.js:如何定义组件的mount()中使用的通用方法,以及如何更改组件的数据

[英]Nuxt.js:How to define common method used in mounted () of component, and change data of component

I want to detect the scroll event in the mounted () of the component as follows, and change the data used in the component. 我想按以下方式检测组件的mount()中的滚动事件,并更改组件中使用的数据。

・component ·零件

<script>
import checkScroll from '~/utils/checkScroll'

export default {
  ...
  data() {
    return {
      scrollPosition: 0
    }
  },
  mounted() {
    window.addEventListener(
      'scroll',
      checkScroll(this.scrollPosition, window.scrollY)
    )
  },
</script>

・utils/checkScroll.js ·utils的/ checkScroll.js

export default function checkScroll(scrollPosition, scrollY) {
  scrollPosition = scrollY
}

There are two issues in this case 在这种情况下有两个问题

1. I want to execute this function each time I scroll, but the function is executed only at the first scroll 我想每次滚动都执行此功能,但是该功能仅在第一次滚动时执行
2.The value of this.scrollPosition inside component does not change. 2.组件内部的this.scrollPosition值不变。

If this is the case, how will it work? 如果是这样,它将如何运作?

The first issue shouldn`t happen. 第一个问题不应该发生。 if u add eventListener it will be executed every time you scroll and i have checked locally it works as expected. 如果您添加eventListener,它将在您每次滚动时执行,并且我在本地进行了检查,它可以按预期工作。 But you should pass a function to event listener, but you are passing already executed function. 但是您应该将一个函数传递给事件侦听器,但是您要传递已经执行的函数。

You could return result from it and do something like this 您可以从中返回结果并执行类似的操作

export default function checkScroll(event) {
  return window.scrollY;
}

mounted() {
    window.addEventListener("scroll", event => {
      this.scrollPosition = checkScroll(event);
    });
  }

Here CBS with working example https://codesandbox.io/s/0qjkoox68v 这里是CBS的工作示例https://codesandbox.io/s/0qjkoox68v

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM