【问题标题】:How to rerun a Vuex Getter如何重新运行 Vuex Getter
【发布时间】:2018-07-26 08:54:53
【问题描述】:

也许我误解了 Vuex 中的 getter 是什么,但假设我有一个获取 DOM 元素大小的 getter,例如 div。我会做这样的事情:

const getters = {
  getContainerWidth (state) {
    return document.getElementById('main-content').clientWidth;
  }
}

现在,当我启动我的应用程序时,所有的 getter 似乎都被立即运行了。如果 div 在启动时不可用怎么办?如何重新运行吸气剂?

我现在像这样运行吸气剂:

import store from '@/store'
store.getters['myModule/getContainerWidth']

我想也许这会起作用:

store.getters['myModule/getContainerWidth']()

但是由于 store.getters 是一个包含属性和值的对象,而这些值不是函数,所以我不能重新运行它们。

有什么想法吗?

【问题讨论】:

    标签: javascript vue.js vuex


    【解决方案1】:

    Getter 应该依赖于 state 字段来响应。如果您想观察clientWidth 的变化 - 它不起作用。

    如果你想像函数一样使用它,那么只需从 getter 中返回函数:

    const getters = {
      getContainerWidth (state) {
        return () => {
           let container = document.getElementById('main-content');
           return container ? container.clientWidth : 0
        };
     }
    

    }

    并像getContainerWidth()一样使用它

    【讨论】:

      猜你喜欢
      • 2017-04-13
      • 2020-05-26
      • 2021-03-28
      • 2017-12-24
      • 2018-10-18
      • 2019-06-29
      • 2019-08-06
      • 2021-02-03
      • 2018-02-22
      相关资源
      最近更新 更多