使用 OpenLayers 和 Vue.js 在地图上添加新控件时出现问题



我正在尝试使用带有 Vue.js 的 OpenLayers 在地图上添加一个自定义控件。

我有一个组件 Explore.vue,它使用 OL 创建我的"映射"(olmap),我通过绑定将其传递到子组件 LeftSideBar2.vue。

当我尝试在映射中添加一个新控件时,Vue 显示以下错误:

[Vue warn]: Error in mounted hook: "TypeError: this.olmap.addControl is not a function"

有人知道发生了什么吗?

我的文件是:

Explore.vue:

模板:

<explore-left-side-bar2 v-bind:olmap="olmap"/>

脚本:

export default {
name: 'Explore',
data () {
return {
olmap: {}
}
},
methods: {
initComponent: function () {
// eslint-disable-next-line
this.olmap = new Map({
target: 'map',
layers: [
baseLayerGroup
],
view: new View({
projection: 'EPSG:4326',
center: [0, 0],
zoom: 5
})
})
}
},
mounted: function () {
this.initComponent()
},
components: {
ExploreLeftSideBar2
}
}

左侧边栏2.vue:

脚本:

export default {
name: 'LeftSideBar2',
props: ['olmap'],
data () {
return {
}
},
methods: {
initComponent: function () {
var sidebar = new Sidebar({ element: 'ol-sb-sidebar', position: 'left' })
this.olmap.addControl(sidebar)      
}
},
mounted: function () {
this.initComponent()
},
components: {
LeftSideBarLayerTree
}
}

看起来你已经将一个对象olmap={}绑定到一个组件,该组件在返回中调用一个函数this.olmap.addControls(),该函数不存在于您作为道具传递的对象上。我认为您正在尝试在OpenLayers.Map实例上调用addControls()。

正如这个答案所解释的那样,mounted钩子是在其父组件之前为子组件调用的,这意味着当olmap仍然是Explore.vuedata方法中声明的默认空对象时,LeftSidebar2.vue将调用this.olmap.addControl(sidebar)

您可以通过多种方式解决此问题:

您可以在Explore.vuecreated钩子中初始化olmap,而不是mounted钩子。

您可以使用v-if来排除LeftSidebar2.vue,直到初始化olmap

最新更新