在Vuex中使用NuxtJS Strapi模块

问题描述

我使用@nuxt/strapi作为Strapi的{​​{1}}的包装。 对于Nuxt内部的Vuex,我使用的是命名空间模块模式,因此我的结构如下所示:

NuxtJS

一个store ├── user.js ├── posts.js └── index.js 项目中,我将导入Vue,Vuex或Axios,然后创建一个商店实例Vue并调度我的初始动作或从const store = new Vuex.Store(storeOptions)内部进行一些API调用。 / p>

vue项目中index.js的示例:

store/index.js

但是在Nuxt项目中,商店和bandi实例已经在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"); ... } 中创建。那么在root_project/.nuxt/...中使用$ strapi和$ store的最佳方法是什么? store/index.js中没有$strapi$store

解决方法

打开/刷新页面后,就会在服务器端执行此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...
  }
}

文档说,如果您将trapi模块添加到项目中,则应该能够从上下文中访问它。上下文是nuxtServerInit

中的第二个参数

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

您可以使用

从任何组件分派/提交某些内容
this.$store.commit("SOME_MUTATION")

他们说this.$strapi

可以使用

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