typescript - Vuex ve Composition API kullanarak reaktif özelliklere erişmenin bir yolu var mı?


Bileşenimi şöyle tasarlarsam:

<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>

Ve mağazam şöyle tanımlanmıştır:

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;
  }
}

Şablonda {{ store.getters.count }} yerine sayıya daha iyi bir şekilde erişebileceğim bir yol var mı? İdeal olarak, ona sadece {{ count }} şeklinde erişmek isterdim, ama görünüşe göre sadece store reaktif. Başka bir deyişle, increment aksiyonunu dispatch etsem bile, count'u farklı şekillerde tanımlamaya çalışsam da ``{{ count }}`` güncellenmiyor. İşte denediğim bir şey:

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

Bu durumda {{ count }} neden reaktif değil?

Cevap #1

count: store.getters.count, store.getters.count değerini state count'unuzun varsayılan değeri olarak sakladığınız anlamına gelir.

Bu, tepkisel olmayacağı anlamına geliyor. Dikkat edin, mağazada count bir fonksiyondur.

Durumunuz count'u bunun yerine hesaplanmış bir özellik yapmayı deneyebilirsiniz, böylece düzgün bir şekilde güncellenir.

Henüz Composition API'yi denemedim, ama umarım yardımcı olabilirim.