VueJS 版本 1.9.0
app.js
require('./bootstrap');
window.Vue = require('vue');
Vue.component('mapbox', require('./components/mapbox.js'));
const app = new Vue({
el: '#app'
});
components/mapbox.js
// initially from https://github.com/phegman/vue-mapbox-gl/blob/master/src/components/Mapbox.vue
export default {
data() {
return {
_map: null
};
},
props: {
accessToken: {
type: String,
required: true
},
mapOptions: {
type: Object,
required: true
},
navControl: {
type: Object,
default: () => {
return {
show: true,
position: 'top-right'
};
}
},
geolocateControl: {
type: Object,
default: () => {
return {
show: false,
position: 'top-left',
options: {}
};
}
},
scaleControl: {
type: Object,
default: () => {
return {
show: false,
position: 'top-left',
options: {}
};
}
},
fullscreenControl: {
type: Object,
default: () => {
return {
show: false,
position: 'top-right'
};
}
}
},
mounted() {
const map = this.mapInit();
this._map = map;
this.registerEvents(map);
},
methods: {
mapClicked(map, e) {
console.log("clicked");
},
mapInit() {
mapboxgl.accessToken = this.accessToken;
if (!this.mapOptions.hasOwnProperty('container')) {
this.mapOptions.container = 'map';
}
const map = new mapboxgl.Map(this.mapOptions);
this.$emit('map-init', map);
return map;
},
registerEvents(map) {
map.on('load', () => {
this.$emit('map-load', map);
});
map.on('click', e => {
this.$emit('map-click', map, e);
});
map.on('render', () => {
this.$emit('map-render', map);
});
}
},
beforeDestroy() {
this._map.remove();
}
};
index.blade.php
<mapbox
access-token="MY-ACCESS-TOKEN"
:map-options="{
style: 'mapbox://styles/mapbox/light-v9',
center: [-96, 37.8],
zoom: 3
}"
:geolocate-control="{
show: true,
position: 'top-left'
}"
:scale-control="{
show: true,
position: 'top-left'
}"
:fullscreen-control="{
show: true,
position: 'top-left'
}"
@map-click="mapClicked"
inline-template>
<div id="map"></div>
</mapbox>
从 index.blade.php 我正在尝试调用 @map-click="mapClicked"
,它位于 components/mapbox.js的方法
但是我得到了错误
▶ app.js:36934 [Vue warn]: Property or method "mapClicked" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
▶ [Vue warn]: Invalid handler for event "map-click": got undefined
- 我知道如果我将
mapClicked
移动到 app.js:const app = new Vue({el: '#app', methods: {mapClicked (){..}}});
它会起作用,但我希望我的文件干净,并会尽量避免这种解决方案。 - 我读到这个:Vue inline template not finding methods or data但它对我不起作用。
最佳答案
当您将 inline-template
属性添加到组件的标签时,组件标签内的所有 都将用作组件的模板,并限定为组件的 Vue 实例。但是,标签本身的范围仍然限于父级。因此,正如预期的那样,警告告诉您父组件没有 mapClicked
方法。
您应该简单地调用您在 registerEvents
方法中设置的点击处理程序中的 mapClicked
方法:
map.on('click', e => {
this.mapClicked(map, e);
this.$emit('map-click', map, e);
});
关于javascript - 从 VueJS 中的 "inline-template"调用组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54929855/