[英]Using the NuxtJS Strapi Module in Vuex
I am using @nuxt/strapi
as a wrapper around Strapi
for NuxtJS
.我使用
@nuxt/strapi
周围的包装Strapi
为NuxtJS
。 For Vuex inside Nuxt I am using the namespaced modules mode, so my structure looks as an example like this:对于 Nuxt 中的 Vuex,我使用的是命名空间模块模式,所以我的结构看起来像这样:
store
├── user.js
├── posts.js
└── index.js
In a Vue
project I would import Vue, Vuex, maybe Axios and then create a store instance const store = new Vuex.Store(storeOptions)
and dispatch my initial actions or make some API calls from inside store/index.js
.在
Vue
项目中,我会导入 Vue、Vuex 或 Axios,然后创建一个 store 实例const store = new Vuex.Store(storeOptions)
并分派我的初始操作或从store/index.js
内部进行一些 API 调用。
Example for index.js in a vue project: 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");
...
}
But in a Nuxt project the store and the strapi instances already were created in root_project/.nuxt/...
.但是在 Nuxt 项目中,商店和 Strapi 实例已经在
root_project/.nuxt/...
中创建。 So what is the best way to use $strapi and $store inside store/index.js
?那么在
store/index.js
使用 $strapi 和 $store 的最佳方法是什么? Neither $strapi
or $store
are available in store/index.js
$strapi
或$store
在store/index.js
都不可用
there is this nuxtServerInit
action that gets executed on the server side after you open / refresh page.打开/刷新页面后,在服务器端执行此
nuxtServerInit
操作。
You can only do it in index.js
file你只能在
index.js
文件中做
This is how your index.js could look like:这就是你的 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...
}
}
The documentation says if you added the strapi module to your project, you should be able to access it from the context.该文档说,如果您将trapi 模块添加到您的项目中,您应该能够从上下文访问它。 The context is the second argument from
nuxtServerInit
上下文是来自
nuxtServerInit
的第二个参数
Thats it.就是这样。 This is how a store could look like, nothing fancy.
这就是商店的样子,没什么特别的。
You could dispatch / commit something from any component with你可以从任何组件发送/提交一些东西
this.$store.commit("SOME_MUTATION")
They say its global available with this.$strapi
他们说它的全局可用
this.$strapi
This module globally injects $strapi instance, meaning that you can access it anywhere using this.$strapi.
这个模块全局注入了 $strapi 实例,这意味着你可以在任何地方使用 this.$strapi 访问它。 For plugins, asyncData, fetch, nuxtServerInit and Middleware, you can access it from context.$strapi.
对于插件,asyncData、fetch、nuxtServerInit 和 Middleware,你可以从 context.$strapi 访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.