将数组数据传递给组件并制作

Pass array data to component and make

我尝试熟悉 Vue2。 正如您在下面看到的,我尝试传入“标记”-Array,但地图没有改变。如何更改标记数组?如何使标记数组具有反应性,以便地图标记发生变化?

谢谢你的帮助!

views/Map.vue
<template>
  <div id="MapWrapper">
    <Map :markers = "markers"/>
  </div>
</template>

<script>
import Map from 'src/components/MapSoal.vue'

export default {
  name: 'MapView',
  components: {
    Map
  },
  data () {
    return {
      markers: [
        {name: "greenMarker", lngLat: [13.8022177, 51.0069449], color: "green", text: "<h1>This is the green marker</h1>"},
        {name: "orangeMarker", lngLat: [13.8022177 - 0.05, 51.0069449], color: "orange", text: "<h1>this is the orange marker</h1>"},
      ]   
    }  
  }
}
</script>
components/MapSoal.vue
<template>
  <MglMap 
    :accessToken="accessToken" 
    :mapStyle="mapStyle" 
    :center="center"
    :zoom="zoom"
  >
    <MglMarker v-for="marker in markers" :key="marker.name" :coordinates="marker.lngLat" :color="marker.color">
       <MglPopup>   
          <VCard v-html="marker.text"></VCard>
        </MglPopup>
    </MglMarker>
   <MglGeolocateControl></MglGeolocateControl>
   <MglNavigationControl></MglnavigationControl>
  </MglMap>
</template>

export default {
    data() {
        return {
          accessToken: 'SOME_API_KEY',
          mapStyle: 'mapbox://styles/mapbox/streets-v11?optimize=true',
          center: [13.8022177, 51.0069449],
          zoom: 9, // starting zoom
          markers: []
        };
      },    
        
    }

您没有在 Map 组件中将 markers 声明为道具,而是在数据对象中声明标记,因此 Map 组件有一个单独的数据变量named markers,与你父组件的数据完全无关。尝试从 Map 组件中的数据中删除 markers 数组,并将其添加到组件中的 props 对象中,如下所示:

props: {
    markers: {
        type: Array
    }
},

props: ['markers'],

所以你的 Map 组件看起来像这样:

<template>
  <MglMap 
    :accessToken="accessToken" 
    :mapStyle="mapStyle" 
    :center="center"
    :zoom="zoom"
  >
    <MglMarker v-for="marker in markers" :key="marker.name" :coordinates="marker.lngLat" :color="marker.color">
       <MglPopup>   
          <VCard v-html="marker.text"></VCard>
        </MglPopup>
    </MglMarker>
   <MglGeolocateControl></MglGeolocateControl>
   <MglNavigationControl></MglnavigationControl>
  </MglMap>
</template>

export default {
    props: ['markers'],

    data() {
        return {
          accessToken: 'SOME_API_KEY',
          mapStyle: 'mapbox://styles/mapbox/streets-v11?optimize=true',
          center: [13.8022177, 51.0069449],
          zoom: 9, // starting zoom
        };
      },    
        
    }