簡體   English   中英

如何將 Vuex 集成到 Storyblok 插件中?

[英]How can I integrate Vuex into a Storyblok plugin?

我正在用 vue 為 storyblok 構建一個插件。 我決定將 state 管理添加到插件而不是$emit()的回聲室一直備份組件樹會更容易。 我將 Vuex 安裝到我的插件中,然后按照 Vuex 教程中的說明將其添加到main.js文件中,但是我的main.js文件沒有像常規 Vue 應用程序的main.js文件那樣設置。

本教程告訴我們這樣做

import Vue from 'vue'
import App from './App.vue'
import store from './store' //our Vuex store

Vue.config.productionTip = false

new Vue({
    store, //passing in our store
    render: h =>(App)
}).$mount('#app')

但是,由於是 storyblok 插件,我的main.js文件看起來像這樣

import Plugin from './Plugin.vue'
import store from './store'  //I have no clue where to put this in the code below :(

if (process.env.NODE_ENV == 'development') {

  window.Fieldtype = Plugin
  let customComp = window.Storyblok.vue.extend(window.Fieldtype);
  window.Storyblok.vue.component('custom-plugin', customComp);
  window.StoryblokPluginRegistered = true;

} else {
  
  let init = Plugin.methods.initWith() 
  window.storyblok.field_types[init.plugin] = Plugin

}

如您所見,設置完全不同,因為它旨在將 Vue 組件作為插件注入 storyblok,而不是設置新的 Vue 應用程序。 有人知道我應該在這里做什么嗎?

我解決了這個問題,在 main.js 中添加了這一行: main.js window.Storyblok.vue.$store = store;

然后在您調用商店時在您的插件中使用相同的方法。 例如: window.Storyblok.vue.$store.commit()

所以我還在學習 StoryBlok 和他們的插件開發,所以如果這是錯誤的,請對我大喊大叫。

我能夠像這樣解決這個問題。

僅在某些情況下,這是我的一般文件夾結構。

.
└── my-app/
    ├── node_module/
    │   └── ...
    ├── public/
    │   └── index.html
    └── src/
        ├── store/
        │   ├── state.js
        │   └── config.js
        ├── main.js
        └── Plugin.vue

main.js

import Vuex from 'vuex'
window.Storyblok.vue.use(Vuex); // This has to come before the Plugin import
import Plugin from './Plugin.vue'

if (process.env.NODE_ENV == 'development') {

  window.Fieldtype = Plugin

  let customComp = window.Storyblok.vue.extend(window.Fieldtype);
  window.Storyblok.vue.extend(window.Fieldtype);
  window.Storyblok.vue.component('custom-plugin', customComp);
  window.StoryblokPluginRegistered = true;

} else {

  let init = Plugin.methods.initWith()
  window.storyblok.field_types[init.plugin] = Plugin

}

插件.vue

import Vuex from 'vuex';
import State from './store/state';

const store = new Vuex.Store(State);

export default {
  name: 'my-vue-plugin',

  mixins: [window.Storyblok.plugin],

  store: store,

  components: {},

  data() {
    return {}
  },
};

state.js

import Config from './config';

export default {
    modules: {
        Config
    },
    state: {
        count: 0
    },
    mutations: {
        increment(state) {
            state.count++
        }
    }
};

然后在你的嵌套組件中的任何地方或任何你可以調用increment突變的地方,像這樣this.$store.commit('increment');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM