openlayers+vue初学注意点

当我们使用 vue 开发 openplayers 的时候,总是会下意识的使用 ref 来代理openplays 中的 变量, 这种方法是不可取的, 很容易发生我们想不到的错误

下面看一段我最初写的,理论正确,但实际用不了的代码

javascript 复制代码
<script setup>
import {onMounted, ref} from 'vue'
import Map from "ol/Map"
import TileLayer from "ol/layer/Tile.js";
import XYZ from "ol/source/XYZ.js";
import View from "ol/View.js";
import {fromLonLat} from 'ol/proj.js';

const map = ref(null);
const mapRef = ref(null)

const layer1 = ref(null);
const layer2 = ref(null);

onMounted(() => {

  layer1.value = new TileLayer({
    source: new XYZ({
      url: "https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}"
    })
  })

  layer2.value = new TileLayer({
    source: new XYZ({
      url: "https://webst01.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}"
    })
  });
  map.value = new Map({
    target: mapRef.value,
    layers: [layer1.value, layer2.value],
    view: new View({
      center: fromLonLat([114.31, 30.52]),
      zoom: 10,
      projection: "EPSG:3857"
    })
  })

})


const removeBJ = () => {
  map.value.removeLayer(layer2.value);
}


</script>

<template>
  <div class="button">
    <!--    <button @click="gotoBJ">跳转到北京</button>-->
    <button @click="removeBJ">remove</button>
  </div>
  <div ref="mapRef" id="map"></div>
</template>

<style scoped>
#map {
  width: 100vw;
  height: 100vh;
}
</style>


所以, 我们在使用 vue+openlayers 的时候,对openlayer 中的对象尽量不要去用 ref来定义

相关推荐
计算机魔术师9 分钟前
OpenAI 砍掉 100 亿融资目标,AI 资本市场的温度计变了
前端
jktantan29 分钟前
(二)Vue 3 的 attrs 不是响应式:el-form 扩展属性同步的三种方案
前端·javascript·vue.js·element-plus
前端 贾公子1 小时前
第 5 章:Codex 从可运行程序到可交付工具
java·前端·数据库
用户360055579001 小时前
Kestrel_VLLM - 26 · 发射空档三步曲:事件计时 → nsys → 判别实验
前端
echome8881 小时前
JavaScript async/await 错误处理:别让 Promise 静默失败
开发语言·前端·javascript·promise
PedroQue992 小时前
v0.2.0 架构升级:class + reactive 重塑状态管理
前端·uni-app
鶴哥只手遮天2 小时前
Angular 22 源码级深度解析-第 02 章 编译链路总览:从模板字符串到 `ɵɵ` 指令
前端·开源·angular.js
尘世中一位迷途小书童2 小时前
别再堆万字 Prompt:用 Agent Skills 给团队写一个「前端 Review」Skill
前端·ai编程·cursor
aixingpan2 小时前
aixingpan.cn API开发文档:api_docs_bichart_common2接口指南
前端·php
super_Omni2 小时前
text/PDF/Word → 解析成纯文本 → 分词 → 词表匹配 → 加权打分 → 低于阈值
前端·chrome