首页 > 解决方案 > 使用 NODE.js REST 后端所需的 VUEX

问题描述

我对前端/后端架构不是很有经验,但我使用 NODE.js 创建了一个简单的 REST 后端,并希望构建一个基于 Vue.js 和 Framework7 的前端。

那么你推荐在那里使用 VUEX 吗?或者您如何处理会话或发送到后端的不同请求?

非常感谢!

标签: restvue.jsfrontendvuex

解决方案


您不必使用 Vuex,但我建议使用 Vuex。这是一个使用 Vuex 和 rest api 的示例。

在商店/actions.js

import {
  fetchSomething,
} from '../api/index.js';

export const actions = {

  getSomething({ commit }) {
    fetchSomething().then((something) => {
      commit('UPATED_SOMETHING', something);
    });
  },

}

在 api/index.js

export const fetchSomething = () => {

  const url = 'Some endpoint';

  return new Promise((resolve) => {
    axios.get(url).then((res) => {
      const data = res.data;
      resolve(data);
    }).catch((err) => {
      console.log(err);
    })
  })
 
}

在 store/mutations.js 中

export const mutations = {

  UPATED_SOMETHING(state, data) {
   state.something = data;
  },
}

在 store/index.js 中

import { getters } from './getters'
import { actions } from './actions'
import { mutations } from './mutations'

// initial state
const state = {
  something: null,
}

export default {
  state,
  getters,
  actions,
  mutations,
}

在 store/getters.js 中

export const getters = {

  getSomething: state => {
    return state.something;
  },

}

推荐阅读