I can't use a Client Plugins to render an element in a Client Only Tags in Nuxt

Viewed 38

I'm using Nuxt on a project that has a search input in the header.

I Implemented it using Mabpox Geocoder and it works fine but on first page load the search input appears like this enter image description here

When the mounted hook gets executed and the plugin loads the geocoder it looks fine enter image description here

I wanted to use the <client-only> tag to put a placeholder until the real search is fetched But I get this error:

500 can't access property "querySelector", geocoderContainer is null

Search.vue:

<template>
  <div> 
    <client-only>
      <div :id="geocoderID" @resultFound="resultFound"></div>
    </client-only>
  </div>
</template>

<script>
export default {
  computed: {
    geocoderID() {
      return `mapbox-geocoder-${this.containerID}`;
    },
  },

  mounted() {
    this.$mapboxMaps.createGeocoder(this.geocoderID);
  },
}
</script>

My Mapbox.client.js plugin:

import "mapbox-gl/dist/mapbox-gl.css";
const mapboxgl = require("mapbox-gl");
import MapboxGeocoder from "@mapbox/mapbox-gl-geocoder";
import "@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css";

export default function (context, inject) {
  inject("mapboxMaps", { createGeocoder });
  mapboxgl.accessToken = <my-access-token>

  function createGeocoder(containerID) {
    // Only add the search box if there's none (avoid duplications of boxes)
    const geocoderContainer = document.getElementById(containerID);
    if (geocoderContainer.querySelector(".mapboxgl-ctrl-geocoder")) return;

    const geocoder = new MapboxGeocoder({
      accessToken: mapboxgl.accessToken,
      enableEventLogging: false,
      mapboxgl: mapboxgl,
    });

    geocoder.addTo(geocoderContainer);
  }

When I try to log the div to which i want to attach the search using the following

mounted() {
    console.log(this.geocoderID);
    console.log(document.getElementById(this.geocoderID))
    this.$mapboxMaps.createGeocoder(this.geocoderID);
  },

It logs this

mapbox-geocoder-nav-search

undefined

1 Answers

I found the answer in the docs enter image description here

This is what I did

methods: {
  renderSearch(count = 10) {
    this.$nextTick(() => {
      if (document.getElementById(this.geocoderID)) {
        this.$mapboxMaps.createGeocoder(this.geocoderID);
      } else if (count > 0) {
        this.initClientOnlyComp(count - 1);
      }
    });
  },
},

mounted() {
  this.renderSearch();
},

It worked fine, I logged the count just for curiousity and the element was rendered at count = 9.

Related