@Comnox

Ошибка ymaps (Яндекс.Карты) при переписывании на Composition API Vue3?

добрый день, сталкнулся с такой проблемой что при переписывании компонента:

<template>
  <div id="map" />
</template>

<script>
import { mapGetters } from "vuex";

export default {
  name: "Map",
  data: () => ({
    initCoordinate: [55.670559, 37.609218],
  }),
  created() {
    ymaps.ready(this.initMap);
  },
  computed: {
    ...mapGetters(["bigCardsList"]),
    bigCardsListLength() {
      return this.bigCardsList.length;
    },
  },
  watch: {
    bigCardsListLength(newCountOfLength) {
      newCountOfLength
        ? this.bigCardsList.forEach((city) => {
            this.addNewPlacemark(
              [city.coordinates.latitude, city.coordinates.longitude],
              city.city
            );
            this.map.panTo([
              city.coordinates.latitude,
              city.coordinates.longitude,
            ]);
          })
        : this.map.panTo(this.initCoordinate);
    },
  },
  methods: {
    initMap() {
      this.map = new ymaps.Map("map", {
        center: this.initCoordinate,
        zoom: 10,
        controls: [],
      });
    },
    addNewPlacemark(coordinates, hintContent) {
      this.map.geoObjects.add(
        new ymaps.Placemark(coordinates, {
          hintContent: hintContent,
        })
      );
    },
  },
};
</script>


на Composition Api в таком формате, пропадает как я понял контекст для map, так как я в предыдущем варианте я его инициализирую через this.map, а в формате через ref, что-то идет не так:

614989676007e368458265.png

<template>
  <div id="map" />
</template>

<script>
import { computed, ref, watch } from "vue";
import { useStore } from "vuex";

export default {
  name: "Map",
  setup() {
    const store = useStore();
    const map = ref(null);
    const initCoordinate = ref([55.670559, 37.609218]);

    function initMap() {
      map.value = new ymaps.Map("map", {
        center: initCoordinate.value,
        zoom: 10,
        controls: [],
      });
    }

    ymaps.ready(initMap);

    const bigCardsList = computed(() => store.getters.bigCardsList);
    const bigCardsListLength = computed(() => bigCardsList.value.length);

    function addNewPlacemark(coordinates, hintContent) {
      map.value.geoObjects.add(
        new ymaps.Placemark(coordinates, {
          hintContent: hintContent,
        })
      );
    }

    watch(
      () => bigCardsListLength.value,
      (newCountOfLength) => {
        newCountOfLength
          ? bigCardsList.value.forEach((city) => {
              addNewPlacemark(
                [city.coordinates.latitude, city.coordinates.longitude],
                city.city
              );
              map.value.panTo([
                city.coordinates.latitude,
                city.coordinates.longitude,
              ]);
            })
          : map.value.panTo(initCoordinate.value);
      }
    );
  },
};
</script>
  • Вопрос задан
  • 148 просмотров
Пригласить эксперта
Ответы на вопрос 1
@amrskv
Мне помогло объявление карты не как реактивного объекта

https://v3.ru.vuejs.org/ru/api/refs-api.html#shallowref

import { onMounted, ref, shallowRef, watch, nextTick } from 'vue'

const myMap = shallowRef({})


...........
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы