【问题标题】:Vue.js - Use props in single file component script sectionVue.js - 在单个文件组件脚本部分中使用道具
【发布时间】:2017-03-26 08:49:51
【问题描述】:

我是 vue 新手,很难让它正常工作。我为我的谷歌地图 div 制作了一个文件组件:

map.vue:

<template>
    <div id="map" class="col-100">{{searchArea.radius}}</div>
</template>

<script>
    function updateSearchLocation(latlng) {
        this.searchArea.lat = latlng.lat();
        this.searchArea.long = latlng.lng();
    }

    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 15,
            streetViewControl: false,
            mapTypeControl: false,
            zoomControl: false
        });
        google.maps.event.addListener(map, 'dragend', function() {
            updateSearchLocation(map.getCenter());
        });
        addMyLocationButton();
        getMyLocation();
    }

    window.initMap = initMap;

    module.exports = {
        props: {
            searchArea: Object
        }
    }
</script>

此处调用的其他函数(addMyLocationButton、getMyLocation)也在此文件中定义并正常工作。无法访问 updateSearchLocation 函数中的 searchArea 对象。

我的应用根目录中有一个 searchArea 对象:

searchArea: {
    lat: null,
    long: null,
    radius: 2500
}

已成功传递给这个组件(我可以在 vue 开发工具的这个组件上看到它)。我想使用这个 map.vue 组件来更新这个对象,因为在另一个组件中我正在基于这个对象进行 API 调用。

地图正在显示,因此正在调用 initMap。 getMyLocation 方法获取用户的当前位置,然后调用相同的 updateSearchLocation 函数。

像这样加载我的地​​图:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=xxx&callback=initMap"></script>

【问题讨论】:

  • 请将答案标记为已接受。

标签: vue.js vue-component


【解决方案1】:

将函数放入“方法”对象内的导出对象中:

module.exports = {
        props: {
            searchArea: Object
        },
        data: function() {
            return {
                latlng: whatever
            }
        },       
        methods: {
            updateSearchLocation: function(this.latlng) {..... },
            initMap: function() {.. call updateSearchLocation() as this.updateSearchLocation(this.latlng) ... },
        }
    }

【讨论】:

  • 如何使 initMap 可用于窗口?因此可以在加载谷歌地图脚本时调用它。我用加载地图的方式更新了我的初始帖子。
  • 我认为这会有所帮助:link: var App = window.App = new Vue({...});甚至是完整的解决方案:jsfiddle.net/crabbly/o3ahd45z
猜你喜欢
  • 2016-08-09
  • 2018-09-04
  • 2022-12-20
  • 2019-05-26
  • 2017-07-08
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多