Nuxt JS插件能否仅运行一次?

时间:2020-09-01 14:29:49

标签: vue.js vuejs2 vuex nuxt.js

我有几个VueX动作(仅在服务器上运行),并从nuxtServerInit调度。它们向外部服务发出HTTP请求,这使TTFB变慢了。

我想实现一个缓存插件,该插件可以存储和检索Redis的值。目的是避免在对每个请求执行操作时发出HTTP请求。

我首先在nuxt.js配置文件中添加了一行。

{ src: '~/plugins/cache', ssr: true, mode: 'server' },

然后我在resources/plugins/cache.js

中创建了以下内容
import redis from 'redis';

export default ({ app }, inject) => {
  console.log('Creating redis client');
  inject('cache', redis.createClient({
    //options removed for brevity
  }));
}

我运行该应用程序,每次刷新页面时,控制台上都会显示“正在创建redis客户端”。是否可以创建一个在服务器启动时实例化的插件,并且每个请求使用相同的实例?还是如果不可能,实现缓存的最佳方法是什么?

1 个答案:

答案 0 :(得分:5)

您要共享数据/实例时,插件不是正确的选择,因为每次创建新的Vue实例时都会创建(调用)插件,这在服务器上意味着每个请求...

因此,每个服务器只需要实例化一次......就是Nuxt module

modules/cacheModule.js

export default function (_moduleOptions) {
  // any data you want to share between all requests
  const data = {
    message: `Hello from cache - ${new Date().toLocalTimeString()}`
  };

  this.nuxt.hook("vue-renderer:ssr:prepareContext", (ssrContext) => {
    ssrContext.$cache = data;
  });
}

并在服务器插件或nuxtServerInit ...

中使用它

store/index.js

export const state = () => ({
  cache: {}
});

export const mutations = {
  setcache(state, payload) {
    state.cache = payload;
  }
};

export const actions = {
  nuxtServerInit({ commit }, context) {
    commit("setcache", context.ssrContext.$cache);
  }
};

Demo

可以使用相同的技术在服务器/客户端(或两者)的Axios实例上应用axios-extensions包中的cacheAdapterEnhancer,以便保留原始代码(在nuxtServerInit中提取)-更多详细信息here