有多少业务逻辑属于 Vuex?

How much of this business logic belongs in Vuex?

我有一个简单的应用程序,它从 API 中提取产品并将它们显示在页面上,如下所示:

我已将 Vuex 添加到应用程序,这样当路由器将用户移动到特定产品页面时,搜索结果和产品搜索数组不会消失。

搜索本身包含以下步骤:

你懂的。

所有变量都存储在 Vuex 中,按理说所有业务逻辑也应该属于 Vuex,但真的如此吗?

我正在专门讨论访问商店参数,例如 productsExhausted(当没有更多产品可显示时)或 productPage(每次触发无限滚动模块时递增)等.

Vuex 中有多少逻辑,属于哪一类?多少不?

我的印象是 Vuex 仅用于存储,但由于所有数据都位于那里,将其全部取回 Vue 应用程序只是为了将其全部发回似乎是一种过于冗长的方式来解决问题。

Vuex 允许您共享数据!

对于与应用程序状态有关的所有内容,它都非常简单。

All the data that can be used by multiple components should be added to the store.

现在说到业务逻辑,虽然我看官方文档说的不是很清楚,但应该遵循同样的原则。

我的意思是,可以被多个组件使用的逻辑应该存储在actions中。 此外 actions 允许您处理异步操作。知道这一点,你拉取数据的代码肯定应该存储在vuex的动作中。

我认为你应该做的是将请求放在一个动作中,然后改变变量的状态,你的 UI 会自动反映这些变化。

此外,一个很好的应用模式是将大部分逻辑转换为状态逻辑。例如,考虑这个 jumping snowman. In here the click action results on updating a value from the store. Although the interesting part is that one component uses the watch 功能的演示,以便在商店更改时得到通知。这样我们将逻辑保留在组件内部,但将商店用作事件发射器。

var store = new Vuex.Store({
    state: {
    isJumping: 0
  },
  mutations: {
    jump: function(state){
      state.isJumping++;
    }
  }
})


Vue.component('snowman', {
  template: '<div id="snowman" :class="color">⛄</div>',
  computed: {
    isJumping: function(){
      return this.$store.state.isJumping;
    }
  },
  watch: {
    isJumping: function(){
      var tl = new TimelineMax();
      tl.set(this.$el,{'top':'100px'})
      tl.to(this.$el, 0.2, {'top':'50px'});
      tl.to(this.$el, 0.5, {'top':'100px', ease: Bounce.easeOut});
    }
  }
})