// store/index.js import Vue from 'vue' import Vuex from 'vuex' import Axios from '~/plugins/axios.js'; Vue.use(Vuex) const store = () => new Vuex.Store({ state: { author: 'WiseWrong', info: '' }, mutations: { setInfo (state, val) { state.info = val } }, actions: { loadAboutMeInfo ({commit, state}) { return Axios.get(`/about`) .then(res => { console.log('ajax is success') console.log(res.data.info) commit('setInfo', res.data.info) }) .catch(err => { console.log('error') }) } } }) export default store
Nuxt.js 内置引用了 vuex 模块,不需要额外安装
上面的代码中,我在 actions 中写了一个 loadAboutMeInfo() 方法,用来请求 /api/about 接口
然后在 about.vue 页面中调用
// about.vue <template> <section> <div> <img src="https://www.jb51.net/~/assets/about.png" alt=""> </div> <h1>{{$store.state.info}}</h1> </section> </template> <script> export default { fetch({ store }) { return store.dispatch('loadAboutMeInfo') }, name: 'about', data () { return {} } } </script>
成果演示: