【问题标题】:Using the NuxtJS Strapi Module in Vuex在 Vuex 中使用 NuxtJS Strapi 模块
【发布时间】:2021-01-27 15:03:00
【问题描述】:

我使用@nuxt/strapi 作为Strapi 的包装器,用于NuxtJS。 对于 Nuxt 中的 Vuex,我使用的是命名空间模块模式,所以我的结构看起来像这样的示例:

store
├── user.js
├── posts.js
└── index.js

Vue 项目中,我将导入 Vue、Vuex,也许是 Axios,然后创建一个商店实例 const store = new Vuex.Store(storeOptions) 并调度我的初始操作或从 store/index.js 内部进行一些 API 调用。

vue 项目中 index.js 的示例:

import Vuex from 'vuex';
import Vue from 'vue';
import user from './modules/user'
import posts from './modules/posts'
Vue.use(Vuex);
const storeOptions = { ... }
const store = new Vuex.Store(storeOptions)

if (user) {
  ...
  store.dispatch('startPageLoading', 'store');
  store.commit('SET_USER', user);
  await store.dispatch("getSomeData");
  ...
}

但在 Nuxt 项目中,store 和 strapi 实例已经在 root_project/.nuxt/... 中创建。那么在store/index.js 中使用$strapi 和$store 的最佳方式是什么? $strapi$storestore/index.js 中均不可用

【问题讨论】:

  • use .. $store inside store/index.js 是什么意思? store/index.js 已经是一家商店
  • 如果我使用存储模块,我仍然需要在 store/index.js 中执行类似 store.dispatch("something") 的操作
  • 好吧……我猜不是。你能给我更多的背景说明吗
  • 我已经用一些示例代码更新了这个问题。我的问题是我是否必须手动创建商店和 Strapi 实例,或者我可以以某种方式使用 Nuxt 在 .nuxt/... 中已经为我创建的东西
  • 请忽略.nuxt 文件夹,我们不应该更改其中的内容,因为里面有一些内部内容。

标签: vue.js nuxt.js vuex strapi nuxt-strapi


【解决方案1】:

在您打开/刷新页面后,会在服务器端执行此 nuxtServerInit 操作。

您只能在index.js 文件中进行操作

这就是你的 index.js 的样子:

//index.js
export const state = () => ({
   someState: false
})


export const mutations = {
  SOME_MUTATION(state, payload) {
    ...
  }
}

export const actions = {
  SOME_ACTION({ state, commit }, payload) {
     ...
  },
  nuxtServerInit({ commit }, { $strapi }){
     //do here something on the server side...
  }
}

文档说如果你将strapi模块添加到你的项目中,你应该能够从上下文中访问它。上下文是来自nuxtServerInit的第二个参数

就是这样。这就是商店的样子,没什么花哨的。

你可以从任何组件中调度/提交一些东西

this.$store.commit("SOME_MUTATION")

他们说它的全球可用this.$strapi

此模块全局注入 $strapi 实例,这意味着您可以使用 this.$strapi 在任何地方访问它。对于插件、asyncData、fetch、nuxtServerInit 和 Middleware,您可以从 context.$strapi 访问它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-05
    • 2018-06-25
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2022-12-15
    相关资源
    最近更新 更多