【问题标题】:A simple use of nuxtJS with Axios and VueXnuxtJS 与 Axios 和 VueX 的简单使用
【发布时间】:2020-01-05 15:08:04
【问题描述】:

我正在发现 VueJS,但在查询 API 时遇到了麻烦。 有(太多)资源,看起来我遇到的每个教程都有不同的方法。现在我迷路了……

该项目是一个 3 页的小展示。内容由 API 提供,每种语言都有一个端点。我想使用 VueX 来存储数据,并根据语言切换交互进行更新。

根据文档,“经典”方法已被弃用,我使用“模块”方法。不过,我认为将数据集中在存储根目录是可以的,因为只需要一个 API 调用:

/store/index.js

import axios from "axios";

// STATE - Initial values
export const state = () => ({
  content: {}
});

// ACTIONS - Asynchronous operations
export const actions = () => ({
    async nuxtServerInit({ commit }) {
    // I will introduce the language variable later here
    const response = await this.$axios.$get('https://APIURL.com/fr');
    const content = response.data;
    commit("setContent", content);
  }
});

// MUTATIONS - Updates the state
export const mutations = {
  setContent(state, content) {
    state.content = content;
  }
};

此时,我希望内容可用于不同的页面或组件。

/components/A_component.vue 和/或/pages/index.vue

...
  {{ content }}
...

// LOADS the store
import { mapState } from "vuex";

// COMPUTES the values retrieval
export default {
  computed: mapState(["content"])
};

但是,没有显示任何内容。确实,content 对象没有更新并且保持为空。

【问题讨论】:

  • 一个动作需要通过调用dispatch来触发。你在任何地方都这么叫吗?内容是否也需要存储在 Vuex 中(即是否可以只在每个页面上获取)?
  • 是的,这一定是个问题。我还没有派件。但我真的不明白如何处理它。使用 nuxt,语法不同,我没有任何 store 对象,如 VueX 文档中所示。实际上,documentation of NuxtJS 指的是 dispatch 内的 nuxtServerInit... 另外,关于获取,我想只执行一个 API 调用而不是每页一个会更有效。抓取是否意味着多次调用?

标签: vue.js axios vuex nuxt.js


【解决方案1】:

好的,我终于找到了错误的来源。

actions 应该导出为对象,而不是函数:

export const actions = {
    async nuxtServerInit({ commit }) {
    // I will introduce the language variable later here
    const response = await this.$axios.$get('https://APIURL.com/fr');
    const content = response.data;
    commit("setContent", content);
  }
};

【讨论】:

    【解决方案2】:

    nuxtServerInit 示例

    // store/settings.js
    export const mutations = {
      GET_PRICE_VIEW_FROM_SERVER(ctx, payload) {
        ctx.priceView = payload;
      }
    }
    
    // store/index.js
    import { getPriceView } from "../utils/getSettings";
    
    export const actions = {
      nuxtServerInit({ commit }, { req }) {
        commit("setting/GET_PRICE_VIEW_FROM_SERVER", getPriceView(req));
      }
    };
    

    使用nuxtServerInit 通常只用于https://nuxtjs.org/api/context#the-context 我认为您的 params.lng 应该来自上下文

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 2018-06-25
      • 2020-06-05
      • 2020-01-17
      • 2020-03-21
      • 2020-03-25
      • 2021-01-27
      • 2019-12-06
      • 2017-10-11
      相关资源
      最近更新 更多