0
votes

So, I wanted to bind style with the height of another element that I got from getHeight function, but I kept getting an error that said window is not defined.

Can someone please give me a solution?

Here is my source code:

<template>
  <div class="container">
    <p class="section-title">past event</p>
    <div class="columns is-multiline">
      <div
        class="column is-one-third is-centered past-events"
        v-for="(event, index) in events.slice(0, 2)"
        :key="index"
      >
        <EventCard :event="event" />
      </div>
      <div class="column is-one-third is-centered">
        <div class="link-box" :style="{ height: getHeight() }">
          <nuxt-link to="/past-events">
            <p style="color: #ffffff; cursor: pointer" class="see-all">
              Lihat List Event Lainnya
            </p>
          </nuxt-link>
        </div>
      </div>
    </div>
    <a class="see-all-btn"> </a>
  </div>
</template>

<script>
import EventCard from "~/components/EventCard.vue";

export default {
  name: "PastEvents",
  components: {
    EventCard
  },
  props: ["events"],
  data() {
    return {};
  },
  mounted() {
    this.getHeight();
  },
  methods: {
    getHeight() {
      const height = window.getComputedStyle(
        document.querySelector(".past-events")
      ).height;
      console.log(height);
      return height + "px";
    }
  }
};
</script>
2

2 Answers

0
votes

Nuxt uses server-sided rendering. This means that when your code is being executed on the server, it does not have something like window. After all, it is not a browser.

The easiest way around this is by wrapping anything that should not be pre-rendered to html, with something like vue-no-ssr. This particular library renders a dummy component on the server, then actually renders the component when it gets to the browser.

0
votes

Yes window doesn't exist during the mounted lifecycle hook. I assume you're trying to place something based on its position?

In that case, you might be able to utilize CSS to do it for you. You can place elements using the View Height/View Width units. Combine that with CSS calc() and you might get the solution you need.

Example:

.element {
  /* make element positon relative to the window */
  position: fixed;
  /* set position - note vw/vh are % of window */
  /* this put the top of your element -200px from the bottom of your window */
  top: calc(100vh - 200px);
}

If you're doing something more complex, using Javascript's element.getBoundingClientRect() will likely provide what you need. See this answer for more info.