You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中为对象赋值时派生属性值无法持久化的问题求助

问题描述

尝试创建对象用于Ionic Capacitor Google Maps API初始化配置地图,但所用ref的值无法持久化,会恢复为默认值。

代码示例

<script setup lang="ts">
import { computed, ref, onMounted } from "vue";
import { Geolocation } from "@capacitor/geolocation";

const currPos = ref<any | null>(null);
const lat = ref<number>(1);
const lng = ref<number>(2);

const getLocation = async () => {
  console.log("got getLocation event");
  currPos.value = await Geolocation.getCurrentPosition({
    enableHighAccuracy: true,
    timeout: 20000,
  });
  lat.value = currPos.value.coords.latitude;
  lng.value = currPos.value.coords.longitude;
};

const centerLat = computed(() => (lat.value ? lat.value : 3));

const mapConfig = {
  center: {
    // 地图初始渲染位置
    // lat: 32.78025, // 这样写有效
    // lng: -117.19335, // 这样写有效
    lat: centerLat.value as number, // 无效,始终为1
    lng: lng.value as number, // 无效,始终为2
  },
  zoom: 10,
};

const logLocData = () => {
  console.log("Latitude", lat.value); // 显示正确的纬度值
  console.log("Longitude", lng.value); // 显示正确的经度值
  console.log("Center Latitude", centerLat.value); // 显示正确的centerLat值
  console.log("MapCofig", mapConfig); // 错误,纬度为1、经度为2
  console.log("MapCofig Latitude", mapConfig.center.lat); // 错误,纬度为1
  console.log("MapCofig Longitude", mapConfig.center.lng); // 错误,经度为2
};

onMounted(() => {
  console.log("mounted");
  getLocation();
});
</script>

控制台日志

mounted
got getLocation event
Latitude 32.7822162
Longitude -117.1852825
Center Latitude 32.7822162
MapCofig {center: {…}, zoom: 10}
MapCofig Latitude 1
MapCofig Longitude 2
解决方案

问题核心是mapConfig是普通JavaScript对象,初始化时仅读取一次lat、lng和centerLat的初始值(1和2)。后续通过getLocation更新ref值时,mapConfig不会自动同步变化。

方案一:将mapConfig转为计算属性

利用Vue响应式特性,把mapConfig定义为计算属性,依赖的ref值变化时会自动重新计算:

const mapConfig = computed(() => ({
  center: {
    lat: centerLat.value as number,
    lng: lng.value as number,
  },
  zoom: 10,
}));

使用时需通过mapConfig.value访问配置对象。

方案二:获取位置后手动更新mapConfig

在getLocation函数中,获取到新经纬度后直接修改mapConfig.center的属性值:

const getLocation = async () => {
  console.log("got getLocation event");
  currPos.value = await Geolocation.getCurrentPosition({
    enableHighAccuracy: true,
    timeout: 20000,
  });
  lat.value = currPos.value.coords.latitude;
  lng.value = currPos.value.coords.longitude;
  // 手动更新mapConfig的中心坐标
  mapConfig.center.lat = lat.value;
  mapConfig.center.lng = lng.value;
};

这种方式保持mapConfig为普通对象,通过主动赋值实现更新。

内容的提问来源于stack exchange,提问作者Essentia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 14:47:45