准备工作
确认自己电脑是否通过npm正确安装了OpenLayers,没有的话可以
npm i openlayers -s
搞定后开始下一步。
注册全局变量
首先全局引入,然后通过vue的prototype方法定义全局变量。
import ol from ‘openlayers‘;
import ‘openlayers/css/ol.css‘;
Vue.prototype.$ol = ol;
这里的Vue.prototype.$ol实际上是“为Vue对象添加了原型属性”,当这个原型属性被用于引用时,它可以视作“全局变量”,使$ol在每个Vue实例中可用。
Vue.prototype用于需要在多个地方使用,但不想污染全局作用域的情况,常用于方法和变量。
这里的$符号用于约定在Vue所有实例中都可用的属性。这样做可以避免与已被定义的数据、方法、计算属性等产生冲突。
疑惑的话可以参考Vue官方教程的这篇文章
在组件中使用
就是使用
let ol = this.$ol;
后面在methods中正常写OpenLayers就可以了。
methods: {
createMap()
{
let ol = this.$ol;
new ol.Map({
layers: [
new ol.layer.Tile({
opacity: 1,
source: new ol.source.XYZ({
projection: "EPSG:4326",
url: "https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png"
})
})
],
view: new ol.View({
center: [0, 0],
zoom: 2,
projection: "EPSG:4326"
}),
target: "map"
});
}
},
在mounted()中调用
mounted() {
this.createMap();
},
至此愉快结束~
原文:https://www.cnblogs.com/yonniye/p/14296479.html