rigor789 / vue-scrollto

Adds a directive that listens for click events and scrolls to elements.
https://vue-scrollto.rigor789.com/
MIT License
2.07k stars 99 forks source link

using this.$scrollTo in nuxt / typescript #321

Open avxkim opened 4 years ago

avxkim commented 4 years ago

There's an issue when using with nuxt (2.13.3) / typescript (@nuxt/types => 2.13.3)

If i don't import vue-scrollto inside my global.d.ts file:

import 'vue-scrollto'

Then using this.$scrollTo inside a component would complain about:

"Property '$scrollTo' does not exist on type 'CombinedVueInstance<Vue, Data, { setActive(index: number, id: number): void; findArticles: ((this: any, val: string) => Promise) & Cancelable; hideResults(): void; showArticle(articleId: number, categoryId: number): Promise<...>; }, unknown, Readonly<...>>'.Vetur(2339)"

picbenoit commented 3 years ago

@webcoderkz

For sure too late, but you need to add "vue-scrollto" to the types in your tsconfig.json file.

"types": [
  "@types/node",
  "@nuxt/types",
  "@nuxtjs/axios",
  "vue-scrollto",
]

If it can help someone.

vinayakkulkarni commented 3 years ago

FYI, for folks who wanna use it with Nuxt + TS + Vue Composition API /plugins/scroll-to.ts:

import { getCurrentInstance } from '@vue/composition-api';

export function useScrollTo() {
  const { $scrollTo } = getCurrentInstance();

  if (!$scrollTo) {
    // throw error, no store provided
    throw new Error('Nuxt $scrollTo is not defined!');
  }
  return $scrollTo;
}

add it to plugins: [] in nuxt.config.(j|t)s:


  plugins: [
    // ...
    { src: '~/plugins/scroll-to', mode: 'client' },
    // ...
  ],
  modules: [
    // ...
    // Docs: https://vue-scrollto.netlify.app/docs/
    'vue-scrollto/nuxt',
    // ...
  ],

and using it in your component:

<template>
  <table>
    <tbody>
      <tr
        v-for="({ id, address }, index) in state.someArray"
        :id="`scroll-${index}`"
        :key="index"
      >
        <td>
          {{ id }}
        </td>
        <td>
          {{ address }}
        </td>
      </tr>
    </tbody>
  </table>
</template>

<script lang="ts">
  import { defineComponent, onMounted, reactive } from '@vue/composition-api';
  import { useScrollTo } from '@/plugins/scroll-to';

  export default defineComponent({
    name: 'VueScrollToDemo',
    setup() {
      const $scrollTo = useScrollTo();
      const state = reactive({
        someArray: [
          {
            id: 1,
            address: 'ABC',
          },
          {
            id: 2,
            address: 'XYZ',
          },
          {
            id: 3,
            address: '123',
          },
        ]
      });

      onMounted(() => {
        scrollToRandom(2);
      });

      function scrollToRandom(idx: number) {
        $scrollTo(`#scroll-${idx}`, 500, {
          container: '.__panel',
          offset: -100,
        });
      }
      return { state };
</script>