我正在尝试使用带有 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.vue
data
方法中声明的默认空对象时,LeftSidebar2.vue
将调用this.olmap.addControl(sidebar)
。
您可以通过多种方式解决此问题:
您可以在Explore.vue
的created
钩子中初始化olmap
,而不是mounted
钩子。
或
您可以使用v-if
来排除LeftSidebar2.vue
,直到初始化olmap
。