我已经试了很多东西了。我曾经尝试过使用nuxt-传单依赖,我尝试过编写我自己的插件并将其包括在内。然而,一切都以“窗口未定义”错误结尾。
映射只应加载到客户端上。
我的vue组件:
<template>
<no-ssr>
<l-map
id="map"
:zoom="zoom"
:min-zoom="3"
:center="center"
>
</l-map>
</no-ssr>
</template>
<script lang="ts">
import Vue from 'vue';
import {latLng, marker} from 'leaflet';
import {ExploreItemType} from '~/components/explore/ExploreItem';
import {Component} from "nuxt-property-decorator";
@Component()
export default class ExplorerMap extends Vue {
url = 'https://api.tiles.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}.png?access_token=pk.eyJ1Ijoia2dydWVuZWJlcmciLCJhIjoiY2puajJ3c3dmMGV1YzNxbDdwZ3Y5MXc0bCJ9.kuHo67NUkzqya1NtSjTYtw';
attribution = 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>';
zoom = 3;
center = latLng(51.505, -0.09);
drawCluster = true;
}
</script>所以我用plugins/vue-folet.ts写了我自己的插件
import Vue from 'vue'
import Vue2Leaflet from 'vue2-leaflet'
import Vue2LeafletMarkerCluster from 'vue2-leaflet-markercluster';
Vue.component('l-circle', Vue2Leaflet.LCircle);
Vue.component('l-geo-json', Vue2Leaflet.LGeoJson);
Vue.component('l-icon-default', Vue2Leaflet.LIconDefault);
Vue.component('l-layer-group', Vue2Leaflet.LLayerGroup);
Vue.component('l-map', Vue2Leaflet.LMap);
Vue.component('l-marker', Vue2Leaflet.LMarker);
Vue.component('l-popup', Vue2Leaflet.LPopup);
Vue.component('l-tile-layer', Vue2Leaflet.LTileLayer);
Vue.component('l-tooltip', Vue2Leaflet.LTooltip);并将其包含在nuxt.config.js中
{src: "~/plugins/vue-leaflet.ts", ssr: false}
无论我尝试了什么,我总是最终得到的窗口不是定义错误。我没有主意了。
发布于 2018-10-31 10:11:12
这是因为在你的组件中
import {latLng, marker} from 'leaflet';这可能会做一些窗口检查,并立即失败。所以您需要使用if (process.client)检查有条件地导入它。
发布于 2018-10-31 14:08:03
多亏了阿尔达伦德的暗示,我才能做到这一点:
<template>
<div>
<no-ssr>
<l-map
id="map"
:zoom="zoom"
:min-zoom="3"
:center="center"
>
<l-tile-layer :url="url" :attribution="attribution"/>
....
</l-map>
</no-ssr>
</div>
</template>
<script lang="ts">
const isBrowser = typeof window !== 'undefined';
let leaflet;
if (isBrowser) {
leaflet = require('leaflet');
}
import Vue from 'vue';
import {Component, Prop, Watch} from "nuxt-property-decorator";
@Component({})
export default class ExplorerMap extends Vue {
url = 'https://api.tiles.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}.png?access_token=pk.eyJ1Ijoia2dydWVuZWJlcmciLCJhIjoiY2puajJ3c3dmMGV1YzNxbDdwZ3Y5MXc0bCJ9.kuHo67NUkzqya1NtSjTYtw';
attribution = 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>';
zoom = 3;
center;
created() {
if (isBrowser) {
this.center = leaflet.latLng(51.505, -0.09);
}
....
}https://stackoverflow.com/questions/53075106
复制相似问题