Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my `client-only` component in nuxt complaining that `window is not defined`?

I have Vue SPA that I'm trying to migrate to nuxt. I am using vue2leaflet in a component that I enclosed in <client-only> tags but still getting an error from nuxt saying that window is not defined.

I know I could use nuxt-leaflet or create a plugin but that increases the vendor bundle dramatically and I don't want that. I want to import the leaflet plugin only for the components that need it. Any way to do this?

<client-only>
   <map></map>
</client-only>

And the map component:

<template>
  <div id="map-container">
    <l-map
      style="height: 80%; width: 100%"
      :zoom="zoom"
      :center="center"
      @update:zoom="zoomUpdated"
      @update:center="centerUpdated"
      @update:bounds="boundsUpdated"
    >
      <l-tile-layer :url="url"></l-tile-layer>
    </l-map>
  </div>
</template>

<script>
import {
  LMap,
  LTileLayer,
  LMarker,
  LFeatureGroup,
  LGeoJson,
  LPolyline,
  LPolygon,
  LControlScale
} from 'vue2-leaflet';
import { Icon } from 'leaflet';
import 'leaflet/dist/leaflet.css';

// this part resolve an issue where the markers would not appear
delete Icon.Default.prototype._getIconUrl;

export default {
  name: 'map',
  components: {
    LMap,
    LTileLayer,
    LMarker,
    LFeatureGroup,
    LGeoJson,
    LPolyline,
    LPolygon,
    LControlScale
  },
//...

like image 458
yam Avatar asked Dec 15 '19 19:12

yam


People also ask

What is client-only Nuxt?

The client-only ComponentThis component is used to purposely render a component only on client-side. To import a component only on the client, register the component in a client-side only plugin.

Is not defined Nuxt js?

To fix the 'document is not defined' error in Nuxt. js, we can wrap our client side code with the client-only component. to wrap the the client side only your-component component with client-only so that it's only rendered in the browser.

Is Nuxt client side?

Nuxt supports both client-side and universal rendering.

How do I use Vue components in Nuxt?

In order to use Vue plugins we need to create a Nuxt plugin and we do this by creating a . js file in the /plugins folder. We then paste in the code that we need to use the plugin. We import Vue and VTooltip and then tell Vue to use the VTooltip.


1 Answers

I found a way that works though I'm not sure how. In the parent component, you move the import statement inside component declarations.

<template>
  <client-only>
    <map/>
  </client-only>
</template>

<script>
export default {
  name: 'parent-component',
  components: {
    Map: () => if(process.client){return import('../components/Map.vue')},
  },
}
</script>
like image 107
yam Avatar answered Sep 20 '22 08:09

yam