简体   繁体   English

在VueJS中访问DOM元素

[英]Accessing DOM element in VueJS

I created the following setup 我创建了以下设置

HTML HTML

<div class="col-md-6">
     <div id="GISMap" v-el:map></div>
</div>

main.js VUE main.js VUE

var Vue = require('vue');
import VueResource from 'vue-resource';
import HomeView from './components/HomeView.vue';

Vue.use(VueResource);
Vue.config.debug = true;

window.app = new Vue({
    el: '.content',

    components: {
        HomeView
    },
    methods: {
        // Broadcast info that API has been loaded. Listen to this in GoogleMaps Module
        init: function() {
             this.$broadcast('MapsApiLoaded');
        }
    }
})

MODULE 1: HomeView.vue 模块1:HomeView.vue

<script>
export default {
    events: {
        MapsApiLoaded: function() {
             // Initialize GIS Map
             initGISMap(this.$els.map);
        }
    }
}
</script>

GoogleMaps.js GoogleMaps.js

function initGISMap(selector) {
    map = new google.maps.Map(selector, {
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
    });

    // Set initial Location and center map to this location
    initialLocation = new google.maps.LatLng(48.184845, 11.252553);
    map.setCenter(initialLocation);

    // Create a searchmarker
    searchMarker = createMarker();

    // Init Autocomplete for GIS
    initAutoComplete();
}

I want to create the map in the div container with the tag v-el:map . 我想在div容器中使用标签v-el:map When I call initGISMap(this.$els.map) within the module, and print out the value in the console, it is empty. 当我在模块中调用initGISMap(this.$els.map)并在控制台中打印出值时,它是空的。 So it seems that I don't have access to this element from within a module? 所以我似乎无法从模块中访问这个元素? How do I need to change this? 我该如何更改?

Overall approach: main.js init() method is broadcasting an info when the map is loaded. 总体方法:main.js init()方法在加载地图时广播信息。 This is caught within the HomeView module and the initGISMap is supposed to be called, residing in the GoogleMaps.js. 这是在HomeView模块中捕获的,应该调用initGISMap,驻留在GoogleMaps.js中。 This is all working fine, but the element to be handed over is missing. 这一切都运行正常,但缺少要移交的元素。

The element is probably not in the scope of your HomeView module. 该元素可能不在HomeView模块的范围内。 The good thing is: vm.$broadcast() can take more than one argument, so you can pass the element directly to the function with 好处是: vm.$broadcast()可以使用多个参数,因此可以将元素直接传递给函数

this.$broadcast('MapsApiLoaded', this.$els.map);

and in HomeView.vue, you can pass it on with 在HomeView.vue中,您可以传递它

export default {
    events: {
        MapsApiLoaded: initGISMap;
    }
}

(You don't have to wrap initGISMap in a closure here.) (您不必在此处关闭initGISMap 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM