1、首先看一下自己的Nuxt的版本 nuxt-v
如何是2.4.0之前的版本, 写法和正常的vue一样
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import geo from './modules/geo'
import home from './modules/home'
Vue.use(Vuex)
const store = () => new Vuex.Store({
modules: {
geo,
home
},
actions: {
async nuxtServerInit({commit}, {req, app}) {
自己要做的事情
}
}
})
export default store
geo.js
const state = () => ({position: {}})
const mutations = {
setPosition(state, val) {
state.position = val
}
}
const actions = {
setPosition: ({commit}, position) => {
commit('setPosition', position)
}
}
export default {namespaced: true, state, mutations, actions}
在组件中使用也是 $store.state.geo.position***这样使用
但是如果你的版本在2.4.0以上,就会以下、出现错误
Classic mode for store/ is deprecated and will be removed in Nuxt 3
"export 'reactive' was not found in 'vue'
所以接下来看重点了
首先1、改动后index.js只写获取数据的逻辑
index.js
export const actions = {
async nuxtServerInit({commit}, {req, app}) {
const {status,data: {province,city}} = await app.$axios.get('/geo/getPosition')
console.log(province, city)
commit('geo/setPosition',status===200?{city,province}:{city:'',province:''})
}
};
老的写法已经不适用
// const store = () => new Vuex.Store({
// modules: {
// geo
// },
// actions: {
//
// }
// });
// export default store
geo.js
//单个全部导出
export const state = () => ({
position: {}
});
export const mutations = {
setPosition(state, val) {
state.position = val
}
};
export const actions = {
setPosition({commit}, position) {
commit('setPosition', position)
}
};
//这里就是index.js中的modules
export const getters = {
setPosition(state) {
return state
}
};
// export default { namespaced: true, state, mutations, actions }
使用方式一样