我为我的索引页面创建了一个 Nuxt 存储,目的是初始化状态并从 API 获取一些数据以改变状态。
这是我商店的代码,包括初始状态、突变和操作。
import Axios from "axios";
//a controller has a store that it interfaces with
// set initial state of the store
const initState = () => ({
message: "init"
})
// make the state usable from other components
export const state = initState
//when you need to change the state
//for mutations you do commits
export const mutations = {
setMessage(state, message) {
state.message = message
}, //can define more functions here
reset(state) {
Object.assign(state, initState())
}
}
//when you have to do API calls (async)
//commit parameter allows us to invoke the mutation functions
//for actions you do dispatch
export const actions = {
async nuxtServerInit({commit}) {
const message = await Axios.get("http://localhost:5000/api/home").data;
console.log(message);
commit("setMessage", message) //put name of mutation as parameter + payload
}
}
在我的 index.vue 文件中,我从 vuex 导入所需的函数并映射状态。
import Logo from '~/components/Logo.vue'
import VuetifyLogo from '~/components/VuetifyLogo.vue'
import Axios from "axios";
import {mapState, mapActions, mapMutations} from 'vuex'
export default {
components: {
Logo,
VuetifyLogo
},
computed: mapState({
message: state => state.message
}),
methods: mapMutations([
"reset",
"setMessage"
])
但是,当我加载页面(使用 Vue 开发工具)时,我的状态开始未定义。我可以通过“重置”方法改变状态,但我的 API 没有被调用来获取数据。我在控制台中没有收到任何错误,所以我不确定是什么原因造成的。我的 API 也已启动并正在运行。
如何确保在加载页面时调用 nuxtServerInit 操作?
MMMHUHU
相关分类