【问题标题】:Using Vuex and the Composition API, is there a way to access reactive properties?使用 Vuex 和 Composition API,有没有办法访问响应式属性?
【发布时间】:2023-04-03 14:40:02
【问题描述】:

如果我这样设计我的组件:

<template>
  <div>
    <button @click="increment">Count is: {{ store.getters.count }}</button>
  </div>
</template>

<script>
import { reactive } from "@vue/composition-api";
import store from "../store";

export default {
  name: "Count",

  setup() {
    const state = reactive({
      store
    });
    const increment = () => {
      store.dispatch.increment();
    };
    return {
      ...state,
      increment
    };
  }
};
</script>

我的商店是这样定义的:

import Vue from "vue";
import Vuex from "vuex";
import { createDirectStore } from "direct-vuex";

Vue.use(Vuex);

const {
  store,
  rootActionContext,
  moduleActionContext,
  rootGetterContext,
  moduleGetterContext
} = createDirectStore({
  state: {
    count: 0
  },
  getters: {
    count: state => state.count
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  actions: {
    increment(context) {
      context.commit("increment");
    }
  }
});

// Export the direct-store instead of the classic Vuex store.
export default store;

// The following exports will be used to enable types in the
// implementation of actions and getters.
export {
  rootActionContext,
  moduleActionContext,
  rootGetterContext,
  moduleGetterContext
};

// The following lines enable types in the injected store '$store'.
export type AppStore = typeof store;
declare module "vuex" {
  interface Store<S> {
    direct: AppStore;
  }
}

有什么方法可以比模板中的{{ store.getters.count }} 更好地访问计数?理想情况下,我只想像{{ count }} 一样访问它,但似乎只有store 是被动的。换句话说,如果我调度增量操作,{{ count }}` 不会更新,即使我尝试以各种方式定义 count。这是我尝试过的一件事:

  setup() {
    const state = reactive({
      store,
      count: store.getters.count
    });
    const increment = () => {
      store.dispatch.increment();
    };
    return {
      ...state,
      count: state.count,
      increment
    };
  }

为什么{{ count }} 在这种情况下没有反应?

【问题讨论】:

    标签: typescript vue.js reactive-programming vuex vue-composition-api


    【解决方案1】:

    count: store.getters.count 表示您将store.getters.count 的当前值存储为您的状态count 的默认值。

    这意味着它不会是被动的。注意 store 中的count 是一个函数。

    您可以尝试将状态 count 改为计算属性,以便正确更新。

    我还没有尝试过 Composition API,但希望能帮上忙。

    【讨论】:

    • 如果我定义了这样的计算 count: computed(() =&gt; store.getters.count) 那么 {{ count }} 仍然没有反应。
    • 你不应该把count放在reactive里面。相反,将其设为变量:const count = computed(() =&gt; store.getters.count) 然后将其包含在您的返回语句中:return { ..., count } 让我知道这是否适合您。
    • 您可以将count 放入reactive 状态。然后:return { state } 并在模板中:{{ state.count }}。 @bkinsey808
    • 不在这里工作,在某些地方工作,但在其他地方不工作。
    猜你喜欢
    • 1970-01-01
    • 2017-04-20
    • 2022-08-23
    • 2022-08-02
    • 2021-05-29
    • 2021-09-10
    • 2016-10-18
    • 2010-09-07
    • 2021-07-05
    相关资源
    最近更新 更多