【问题标题】:What is the difference between Vuex subscribe and getter?Vuex subscribe 和 getter 有什么区别?
【发布时间】:2021-08-24 11:29:15
【问题描述】:

我有一个显示产品信息的Product.vue 组件。每当路由中的ProductIDvuex 中存储的数据发生变化时,它就会更新。这样做是这样的:

setup() {
...
    // function to trigger loading product into vuex store state
        async function loadProduct() {
          try {
            await $store.dispatch('loadProduct', {ProductID: $route.params.ProductID})
          } catch (error) {
            console.log(error);
          }
        }
    
    // watch the route for changes to the ProductID param and run loadProduct() function above
      watch(() => $route.params.ProductID, async () => {
              if ($route.params.ProductID) {
                loadProduct();
              }
            },
            {
              deep: true,
              immediate: true
            }
        )
    // Get the product data using a getter
        const Product = computed(() => $store.getters.getProduct);
}

当我使用上面的代码并转到像localhost:8080/product/123 这样的路线时,const Product 的值是空的,然后在一瞬间它就会有正确的产品数据。如果我再去localhost:8080/product/545这样的另一条路线,const Product的值将是123更新为545之前的旧产品数据。这可能是预期的行为,但它会扰乱 SSR 应用程序,这些应用程序会将旧数据作为 HTML 返回给浏览器。

然后我遇到了解决问题的vuex subscribe function。但我不明白 为什么如何 它与 computed getter 不同。这是代码所需的唯一更改:

setup() {
...
  const Product = ref();
  $store.subscribe((mutation, state) => {
  Product.value = state.productStore.product
  })
}

现在,商店总是在页面呈现之前填充新的产品数据,并且 SSR 也会获取正确的更新数据。为什么这对计算属性更好/不同?

【问题讨论】:

    标签: vue.js vuex vuejs3 vue-composition-api vuex4


    【解决方案1】:

    computed() 是 Vue 内部的,当在其中调用任何 ref 时更新。

    subscribe() 是特定于 Vuex 的,每当调用 any 突变时都会被调用。

    【讨论】:

    • 问题更多是关于为什么computed()subscribe 更慢/延迟,为什么我不能在任何情况下都使用subscribe 而不是computed
    • 1. subscribe 在突变后立即被调用,它会自动允许您直接更新您的值。虽然计算值可能会在此之后更新。但老实说,这只是目前的猜测。 2. 你不想在计算上使用订阅,因为你无法真正控制在你的突变中更改了哪个值,并且每个订阅都会在每个突变上调用,这使得你的代码几乎就像一个只有几个订阅的奇迹盒子。
    猜你喜欢
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 2021-08-01
    • 2011-01-06
    相关资源
    最近更新 更多