To 在 Nuxt 3 中自动安装 Vue 插件 https://nuxt.com/docs/guide/directory-structure/plugins#vue-plugins, 创建一个.js/.ts
文件下<projectDir>/plugins/
(如果需要,创建目录)使用以下样板:
// plugins/my-plugin.js
import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin(nuxtApp => {
nuxtApp.vueApp.use(/* MyPlugin */)
})
Since vue3-openlayers
依赖于取决于window
,该插件只能安装在客户端,所以使用.client.js
扩大。
To load vue3-openlayers
客户端,plugin
文件看起来像这样:
// plugins/vue3-openlayers.client.js
import { defineNuxtPlugin } from '#app'
import OpenLayers from 'vue3-openlayers'
export default defineNuxtPlugin(nuxtApp => {
nuxtApp.vueApp.use(OpenLayers)
})
Create <projectDir>/components/MyMap.vue
与以下示例内容来自vue3-openlayers docs https://vue3openlayers.netlify.app/componentsguide/map/#usage:
// 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>
我们只想渲染MyMap
在客户端,因为该插件只是客户端,所以使用<ClientOnly>成分 https://nuxt.com/docs/guide/directory-structure/components#clientonly-component作为包装器:
// app.vue
<template>
<ClientOnly>
<MyMap />
<template #fallback> Loading map... </template>
</ClientOnly>
</template>
demo https://stackblitz.com/edit/nuxt3-vue3-openlayers?file=plugins%2Fvue3-openlayers.client.js