【发布时间】:2019-03-22 18:23:49
【问题描述】:
我有一个无法从服务调用填充的计算属性更新的 vue 组件。
Feed.vue
<template>
<div class="animated fadeIn">
<h1 v-if="!loading">Stats for {{ feed.name}}</h1>
<h2 v-if="loading">loading {{ feedID }}</h2>
</div>
</template>
<script>
export default {
data: () => {
return {
feedID: false
}
},
computed: {
feed(){
return this.$store.state.feed.currentFeed
},
loading(){
return this.$store.state.feed.status.loading;
}
},
created: function(){
this.feedID = this.$route.params.id;
var fid = this.$route.params.id;
const { dispatch } = this.$store;
dispatch('feed/getFeed', {fid});
}
}
</script>
从 feed 模块调度“feed/getFeed”...
feed.module.js
import { feedStatsService } from '../_services';
import { router } from '../_helpers';
export const feed = {
namespaced: true,
actions: {
getFeed({ dispatch, commit }, { fid }) {
commit('FeedRequest', {fid});
feedStatsService.getFeed(fid)
.then(
feed => {
commit('FeedSuccess', feed);
},
error => {
commit('FeedFailure', error);
dispatch('alert/error', error, { root: true });
}
)
}
},
mutations: {
FeedRequest(state, feed) {
state.status = {loading: true};
state.currentFeed = feed;
},
FeedSuccess(state, feed) {
state.currentFeed = feed;
state.status = {loading: false};
},
FeedFailure(state) {
state.status = {};
state.feed = null;
}
}
}
feedStatsService.getFeed 调用服务,该服务只是运行提取并返回结果。然后 commit('FeedSuccess', feed) 被调用,它运行突变,设置 state.currentFeed=feed,并将 state.status.loading 设置为 false。
我可以看出它已存储,因为该对象显示在 Vue 开发工具中。 state.feed.currentFeed 是服务的结果。但是,我的组件并没有改变以反映这一点。并且在开发工具中也有一个payload在突变下。在开发工具中手动提交 feed/feedSuccess 时,我的组件会更新。
我在这里缺少什么?
【问题讨论】:
-
值得一提的是,你可能想看看 Vuex Getters。使用 getter,您可以根据需要将 getter 映射到组件中,而不是直接从计算属性访问状态。
标签: javascript vue.js vuex