JSFiddle - React, Tailwind, and code Playground

by bolerodan

HTML

<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.css">
<div class="" id="app">
  <router-link to="/">Home</router-link>
  <router-link to="/map">Map</router-link>
  <router-view></router-view>
</div>

CSS

.map {
  width: 100%;
  height: 500px;
}

JavaScript

let cachedMap = null
mapboxgl.accessToken = "pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4M29iazA2Z2gycXA4N2pmbDZmangifQ.-g_vE53SD2WrJ6tFX7QHmA"

const Foo = { template: '<div>foo</div>' }
const Map = {
  created () {
  	console.log('cached map?', cachedMap)
  },
  mounted () {
    if (cachedMap === null) {
      new mapboxgl.Map({
          container: this.$refs.map, // container id
          style: 'mapbox://styles/mapbox/streets-v9', // stylesheet location
          center: [-74.50, 40], // starting position [lng, lat]
          zoom: 9 // starting zoom
      })
    } else {
    	this.$refs.mapContainer.appendChild(cachedMap)
    }
  },
  beforeDestroy () {
    if (cachedMap === null) {
    	cachedMap = this.$refs.map
    }
  },
  render (h) {
    let mapEl = []
    if (cachedMap === null) {
      mapEl.push(h('div', {
        ref: 'map',
        attrs: {
          class: 'map'
        }
      }))
    }
    return h('div', {
      attrs: {
        class: 'map-container'
      },
      ref: 'mapContainer'
    }, mapEl)
  } 
}

const routes = [
  { path: '/', component: Foo },
  { path: '/map', component: Map }
]

const router = new VueRouter({
  routes // short for `routes: routes`
})

const app = new Vue({
	el: '#app',
  router
})