Vue.js - 在单个文件组件脚本部分中使用道具

时间:2017-03-26 08:49:51

标签: vue.js vue-component

我是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对象。

我在app的根目录中有一个searchArea对象:

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

它成功传递给了这个组件(我可以在vue dev工具中的这个组件上看到它)。我想使用这个map.vue组件更新这个对象,因为在另一个组件中我根据这个对象进行API调用。

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

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

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

1 个答案:

答案 0 :(得分:0)

将函数放入'methods'对象中的导出对象中:

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