首页 > 解决方案 > 在 Nuxt 中没有页面刷新的情况下更新的值不会改变

问题描述

我刚开始学习 Vue 和 Nuxt。所以我有一个页面,我可以在其中获取所有订单详细信息并更新订单状态。UI 中显示的订单状态不会异步更新。我怎样才能在这里实现反应?

我需要Current Status : <b>{{ order_details.status.state }}</b>异步更新这里的值。

模板

<template>
  <v-container>
    <v-row>
      <v-col cols="12">
        Current Status : <b>{{ order_details.status.state }}</b>
      </v-col>
    </v-row>
  </v-container>
</template>
<template>
  <v-form>
    <v-container>
      <v-row>
        <v-col cols="12">
          <div class="d-flex align-center justify-end">
            <v-btn
              color="primary"
              class="text-subtitle-2 font-weight-medium"
              @click="updateOrder"
              >Update</v-btn
            >
          </div>
        </v-col>
      </v-row>
    </v-container>
  </v-form>
</template>

脚本

export default {
  async fetch({ store, params }) {
    await store.dispatch("merchant/fetchOrderDetails", {
      id: params.id
    });
    await store.dispatch("fetchMerchants");
    await store.dispatch("fetchAllStatus");
  },
  data() {
    return {
      sortTypes: ["Date", "Distance"],
      selectedSort: "Distance",
      statusId: "",
    };
  },
  computed: {
    ...mapState({
      merchants: "merchants",
      statusList: "statusList"
    }),

    ...mapState("merchant", {
      order_details: "orderDetails"
    }),

  },

  methods: {
    async updateOrder() {
      await this.$axios
        .$patch(
          `/admin-portal/orders/${this.$route.params.id}`,
          {
            statusId: this.statusId
          }
        )
    },
  }
};

店铺

export const state = () => ({
  orderDetails: {}
});

export const mutations = {
  SET_ORDER_DETAILS(state, orderDetails) {
    state.orderDetails = orderDetails;
  }
};

export const actions = {
  async fetchOrderDetails({ commit }, { id }) {
    const orderDetails = await this.$axios.$get(
      `/pharmaceutical/admin-portal/orders/${id}`
    );
    commit("SET_ORDER_DETAILS", orderDetails);
  }
};

标签: vue.jsnuxt.jsvuex

解决方案


你自己已经做了很多了。您需要添加一些小东西。这是一个代码示例,可以帮助您修补您的事物并更新 vuex。

<template>
  ...
  <v-btn @click="updateOrderInsideVuex">
    Update
  </v-btn>
  ...
</template>

<script>
import { mapActions } from 'vuex'

export default {
  methods: {
    ...mapActions('merchant', ['updateOrder']),
    
    async updateOrderInsideVuex() {
      this.updateOrder({ paramsId: this.$route.params.id, statusId: this.statusId })
    }
  }
}
</script>

在您的 vuex 商店(模块)中。

const actions = {
  async updateOrder({ commit }, { paramsId, statusId }) {
    const responseFromBackend = await this.$axios.$patch(`/admin-portal/orders/${paramsId}`, { statusId })
    // remember to populate the vuex store with your result from the backend
    // or make another call to fetch the current state of the API
    commit('SET_ORDER_DETAILS_AFTER_PATCH', responseFromBackend)
  },

当然,您还需要编写SET_ORDER_DETAILS_AFTER_PATCH一个典型的突变,但我想这也取决于您的实际数据。


推荐阅读