我正在使用vuex store
对象构建vue2组件。该组件如下所示:
<template>
<ul id="display">
<li v-for="item in sourceData()">
{{item.id}}
</li>
</ul>
</template>
<script>
export default {
mounted: function () {
console.log('mounted')
},
computed: {
sourceData: function() {
return this.$store.getters.visibleSource
}
}
}
</script>
在主要的javascript条目中,在进程开始时通过ajax调用填充商店:
new Vue({
store,
el: '#app',
mounted: function() {
this.$http.get('/map/' + this.source_key + '/' + this.destination_key)
.then(function (response) {
store.commit('populate', response.data)
})
.catch(function (error) {
console.dir(error);
});
}
});
我没有看到任何错误,当我使用Vue devtools资源管理器时,我可以看到我的组件的sourceData
属性填充了数百个项目。我希望一旦这些数据被填充,我会看到一堆li
行,其中有item.id
,它们出现在页面上。
但是,尽管组件中没有错误和明显好的数据,但我没有看到模板呈现任何内容。
在填充vuex存储后,是否需要使用某种回调来触发组件?
编辑:添加商店代码:
import Vue from 'vue';
import Vuex from 'vuex';
import { getSource, getDestination } from './getters'
Vue.use(Vuex)
export const store = new Vuex.Store({
state: {
field_source: [],
field_destination: []
},
getters: {
visibleSource: state => {
// this just does some formatting
return getSource(state.field_source)
},
visibleDestination: state => {
return getDestination(state.field_destination)
}
},
mutations: {
populate(state, data) {
state.field_source = data.source
state.field_destination = data.destination
}
}
})
编辑2:也许这不是v-for
的问题 - 我没有看到正在渲染的模板,甚至主要的ul
标签,我期望看到(空),即使进一步存在问题脚本。
sourceData
是计算属性,而不是方法。您不需要调用它。不要像v-for="item in sourceData()"
那样使用它,像v-for="item in sourceData"
一样使用它。
除此之外,在您的qazxsw点突变上,您将覆盖观察/反应对象。
要么使用'populate'
:
Vue.set()
或者将所有元素推送到现有的,被观察/被动的数组:
mutations: {
populate(state, data) {
// was state.field_source = data.source
Vue.set(state, 'field_source', data.source);
// was state.field_destination = data.destination
Vue.set(state, 'field_destination', data.destination);
}
}