Javascript Vuejs:从存储区加载topojson并使用d3打印
我面临的问题与这个问题类似: 首先,我想将一些静态topojson文件加载到存储中。这发生在main.js中主vue实例的装载上:Javascript Vuejs:从存储区加载topojson并使用d3打印,javascript,d3.js,vue.js,vuex,Javascript,D3.js,Vue.js,Vuex,我面临的问题与这个问题类似: 首先,我想将一些静态topojson文件加载到存储中。这发生在main.js中主vue实例的装载上: new Vue({ ... mounted () { this.$store.dispatch('topojsonStore/loadMunicipalityTopo', 'static/topojson_data/gem_2014.topojson') } }) 在存储中加载时不会出现问题。在我想要可视
new Vue({
...
mounted () {
this.$store.dispatch('topojsonStore/loadMunicipalityTopo',
'static/topojson_data/gem_2014.topojson')
}
})
在存储中加载时不会出现问题。在我想要可视化此数据的组件中,我可以从存储中很好地访问此数据:
computed: {
getMunicipalityTopo () {
return this.$store.getters['topojsonStore/getMunicipalityTopo']
}
}
我将绘图功能放在组件中的方法下:
methods: {
plotMunicipalities () {
var width = 650,
height = 770
var path = d3.geoPath()
.projection(null) // TODO: fix projections
var svg = d3.select('#map').append('svg')
.attr('width', width)
.attr('height', height)
// Load topojson from store
let topoJsonData = this.getMunicipalityTopo
svg.append('path')
.attr('class', 'municipalities')
.datum(topoJsonData)
.attr('d', path)
}
如果我将其附加到模板中的单击事件,则效果良好,如下所示:
<button @click="plotMunicipalities()">Plot municipalities</button>
我该怎么走?加载存储区中的数据时,如何触发函数?我应该在后面提到,将加载不同的层。有些图层用户无法更改,但对于这个特定图层,用户可以更改它。我应该为这些不同的层使用不同的工作流吗?一种方法是通过创建空的vue实例来设置全局事件总线
var EventBus = new Vue({});
然后,让您的topojsonStore/LoadCommunicipalityToPO
操作返回如下承诺:
actions: {
topojsonStore/loadMunicipalityTopo: ({commit}) => {
return new Promise((resolve, reject) => {
commit(...);
resolve();
});
}
}
new Vue({
...
mounted () {
this.$store.dispatch('topojsonStore/loadMunicipalityTopo',
'static/topojson_data/gem_2014.topojson').then(() => {
EventBus.$emit('store-json-loaded');
})
}
})
created(){
EventBus.$on('store-json-loaded', () => {
this.plotMunicipalities();
});
}
然后分派操作,以便您可以使用成功回调并发出如下事件:
actions: {
topojsonStore/loadMunicipalityTopo: ({commit}) => {
return new Promise((resolve, reject) => {
commit(...);
resolve();
});
}
}
new Vue({
...
mounted () {
this.$store.dispatch('topojsonStore/loadMunicipalityTopo',
'static/topojson_data/gem_2014.topojson').then(() => {
EventBus.$emit('store-json-loaded');
})
}
})
created(){
EventBus.$on('store-json-loaded', () => {
this.plotMunicipalities();
});
}
现在,在要绘制设置的组件的已创建挂钩中,事件侦听器如下所示:
actions: {
topojsonStore/loadMunicipalityTopo: ({commit}) => {
return new Promise((resolve, reject) => {
commit(...);
resolve();
});
}
}
new Vue({
...
mounted () {
this.$store.dispatch('topojsonStore/loadMunicipalityTopo',
'static/topojson_data/gem_2014.topojson').then(() => {
EventBus.$emit('store-json-loaded');
})
}
})
created(){
EventBus.$on('store-json-loaded', () => {
this.plotMunicipalities();
});
}
虽然Vamsi的方法肯定会起作用,但我最终在组件中使用了一个观察者:
watch: {
// Execute draw functions when data in store is done loading
getMunicipalityTopo: function () {
this.plotMunicipalities()
}
很好