带有路由和刷新的 Vuex 逻辑

Vuex logic with routes and refresh

我正在使用 Vue、Vuex 和 Vue-Router 开发一个项目,但我在思考异步操作和组件的流程时遇到了一个大问题。

在我的主要组件中,我发送了一个操作来获取带有 ajax 的项目列表。

我的列表组件从这个 getter:

接收项目数组
allProjects: state => state.projects

这很好用,因为默认状态是一个空数组。我的问题是当我想去路线 project/:id 时,如果项目已经加载,它可以使用此代码:

computed: {
    project () {
        return this.$store.state.fram.projects.find(item => item.id === this.id);
    }
}

但是,如果我在 project/4 途中刷新页面,则没有任何效果。我了解这是因为获取所有项目的操作尚未完成。但我希望 Vue(X) 在填充数组并更新计算的项目变量时能够意识到这一点。这是错误的吗?最好的方法是什么?

在您的 store 中创建 getters return 状态并在您的组件中使用 mapGetters。同时解构所需的吸气剂。

computed: {
    ...mapGetters([
         'your_getter'
       ]),
}

API: https://vuex.vuejs.org/en/getters.html

我同意 Georgi 的观点,将逻辑从计算 属性 转移到存储 getter:

store.js

const getters = {
  project: state => {
    return id => {  // note this passes the id from the component

      return state.fram && state.fram.projects   // in case async not done yet
        ? state.fram.projects.find(item => item.id === id)
        : null

    }
  }
}

myComponent.vue

computed: {
  project () {
    return this.$store.getters.project(this.id) 
  }
}

但不太确定在这种情况下使用 mapGetters