window is not defined error in custom directive

Asked 1 years ago, Updated 1 years ago, 84 views

We are developing the front end at Nxt.js.
In order to make the elements appear fluffy when scrolling, we implement them as described in the Vue.js document below.

Create Custom Scroll Directives

At that time, you get an error window is not defined.I'm in trouble because I don't know the cause and I can't move on.Thank you very much for letting me know.

$yarn dev command to start the local server

Image from Gyazo

plugins/scroll.js

import Vue from 'vue'

Vue.directive('scroll', {
  inserted:function(el, binding){
    letf = function(evt){
      if(binding.value(evt,el)){
        window.removeEventListener('scroll',()=>f,false)
      }
    }
    window.addEventListener('scroll',()=>f)
  }
})

nuxt.config.js

 ~Abbreviated~
 plugins: [
    {
      src: '~plugins/scroll.js',
      ssr —false
    }
]

pages/index.vue

<template>
    <a
      class="return-btn fade-in"
      @click="$vuetify.goTo('#top')"
      v-scroll="handleScroll()"
      :class="{show:isShown}"
    >
      <img
        class="return-btn-img"
        src="~assets/images/return_btn.svg"
        alt="return_button"
      />
    </a>
</template>

<script lang="ts">
Short for short
  methods: {
    handleScroll:function(evt,el){
      if(window.scrollY>50){
        el.setAttribute(
          'style',
          'opacity:1; transform:translate3d(0,-10px,0)'
        )
      }
      return window.scrollY>100
    },
</script>

I tried specifying mode:client for nuxt.config.js on January 15, 2020, but the error statement did not change.

plugins:[
    {
      src: '~plugins/scroll.js',
      mode: 'client'
    }

vue.js nuxt.js

2022-09-30 14:46

1 Answers

This is because the a tag with the v-scroll attribute is rendered on the server side.
Change the a tag to render in the browser surrounded by <client-only>.

<client-only>
<a
  class="return-btn fade-in"
  @click="$vuetify.goTo('#top')"
  v-scroll="handleScroll()"
  :class="{show:isShown}"
>
  <img
    class="return-btn-img"
    src="~assets/images/return_btn.svg"
    alt="return_button"
  />
</a>
</client-only>


2022-09-30 14:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.