Nuxt.js报错:Classic mode for store/ is deprecated and will be removed in Nuxt 3

将Nuxt.js升级到最新版的2.4.0时,终端提示警告:Classic mode for store/ is deprecated and will be removed in Nuxt 3。解决办法如下:

我们先看Nuxt.js的源码,其中有一段代码如下:

  // If store is an exported method = classic mode (deprecated)
  if (typeof store === 'function') {
    const log = (process.server ? require('consola') : console)
    return log.warn('Classic mode for store/ is deprecated and will be removed in Nuxt 3.')
  }

从代码中我们可以看出,它对store做了一个是否方法的判断,如果我们export的是一个方法就会出现本文中的警告信息。那么如何去除警告呢?
如下是出现警告信息的写法(文件路径:store/index.js):

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  token:null,
}

const getters = {
  getToken(state){
    return state.token
  },
}

const mutations = {
  setToken(state, token) {
    state.token = token
  },
}

export const actions = {
    //TODO ajax here
}

const store = () => {
  return new Vuex.Store({
    state,
    getters,
    mutations,
    actions
  })
}

export default store

改成如下的写法就可以了(文件路径:store/index.js):

export const state = () => ({
  token:null,
})

export const getters = {
  getToken(state){
    return state.token
  },
}

export const mutations = {
  setToken(state, token) {
    state.token = token
  },
}

export const actions = {
    //TODO ajax here
}

从上边的内容我们可以看出,Nuxt.js为我们封装并精简了很多,这样为我们节省了更多的时间。我这里的解决办法参考了官方示例:vuex-store-modules

the end

标签: nuxt vue