For automatic installation of a Vue plugin in Nuxt 3, you need to create a .js/.ts
file under <projectDir>/plugins/
(create the directory if it doesn't exist) with the following template:
// plugins/my-plugin.js
import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin(nuxtApp => {
nuxtApp.vueApp.use(/* MyPlugin */)
})
Since vue3-openlayers
relies on window
, the plugin can only be installed on the client side, hence use the .client.js
extension.
If you want to load vue3-openlayers
on the client side, the content of the plugin
file should resemble this:
// plugins/vue3-openlayers.client.js
import { defineNuxtPlugin } from '#app'
import OpenLayers from 'vue3-openlayers'
export default defineNuxtPlugin(nuxtApp => {
nuxtApp.vueApp.use(OpenLayers)
})
Create a
<projectDir>/components/MyMap.vue
file with example content from the
vue3-openlayers
documentation:
// components/MyMap.vue
<script setup>
import { ref } from 'vue'
const center = ref([40, 40])
const projection = ref('EPSG:4326')
const zoom = ref(8)
const rotation = ref(0)
</script>
<template>
<ol-map :loadTilesWhileAnimating="true" :loadTilesWhileInteracting="true" style="height:400px">
<ol-view :center="center" :rotation="rotation" :zoom="zoom"
:projection="projection" />
<ol-tile-layer>
<ol-source-osm />
</ol-tile-layer>
</ol-map>
</template>
<style scoped>
@import 'vue3-openlayers/dist/vue3-openlayers.css';
</style>
We specifically intend to render MyMap
on the client side since the plugin is restricted to client-side usage. To achieve this, utilize the <ClientOnly>
component as a wrapper:
// app.vue
<template>
<ClientOnly>
<MyMap />
<template #fallback> Loading map... </template>
</ClientOnly>
</template>
Check out the demo here