关于 javascript:Vuex 执行异步状态改变后的函数

Vuex Executing Function After Async State Change

我对找到一个示例感到沮丧,因为我认为这对于像 Vuex 这样的东西来说是一个非常常见的用例。

我在 store 上分派一个异步操作以通过 api 填充它。填充此商店后,我需要执行某些操作。

我遇到的每个 Vuex 示例似乎只是处理 UI 的直接更新。但几乎在所有情况下,我还需要执行基于关键组件的操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
state: {
  // initial state values are all falsey
  id: false,
  name: false,
},
getters:   {
  getItem: (state) => {
    return state;
  },
},
actions: {
  setItem({commit}) {
    // async call to get and then commit the state
  }
}

上面是 item store 的相关片段,这是一个非常简单的示例,其中调度 action 的调用通常是从此处未详细说明的组件中调用的。下面是我正在观察要填充的项目的组件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
watch:    {
  item: function (newItem) {
    this.doSomethingWith(newItem);  // this never runs
  }
},
computed: {
  ...mapGetters({
    item: 'getItem',
  }),
},
mounted() {
  console.log(this.item);  // I get an observer of the item object

  // none of items state properties are defined during mounted
},
methods: {
 doSomethingWith(item) {
   // I want to do something here with the set item!!
 }
}

我希望项目状态不会在挂载时设置,因为它是对外部 api 的异步调用。然而,我确实期望的是,当它最终被填充时,观察者会捕捉到它并允许我在组件内运行后续操作。但是手表永远不会触发。

那么我如何跟踪组件中的此类更改并根据其新状态运行操作?


监视永远不会触发,因为代码正在监视从 getItem 返回的对象,即 state 对象,并且对 state 对象的引用没有改变。只有状态对象的属性会改变。如果要触发手表,则需要执行 deep 手表。

1
2
3
4
5
6
7
8
watch:    {
  item: {
    handler:function (newItem) {
      this.doSomethingWith(newItem);
    },
    deep:true
  }
},

根据您的应用程序,这可能不是很高效。您可能希望使用监视状态特定属性的 getter。

或者,从启动异步 API 调用并在成功处理程序中执行您需要的操作的操作返回一个Promise。