详解vue+vuex+koa2开发环境搭建及示例开发(2)

import Vue from 'vue' import Vuex from 'vuex'; Vue.use(Vuex) const state = { json: [], }; const mutations = { setJson(state, db){ state.json = db; } } const actions = { getJson(context){ // 调用我们的后端getJson接口 fetch('http://127.0.0.1:3000/json', { method: 'GET', // mode:'cors', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, }).then(function (res) { if(res.status === 200){ return res.json() } }).then(function (json) { //console.log(typeof Array.from(json), Array.from(json)); context.commit('setJson', Array.from(json)); }) } }; export const store = new Vuex.Store({ state: state, mutations: mutations, actions: actions, })

ok, 代码撸完了。

说说axios

想要把本demo的fetch改为axios方式,要做的工作有以下几处:

1、安装axios、在vuex文件引用axios

npm i axios import axios from 'axios'

2、将fetch部分代码替换为:

const actions = { getJson(context){ axios.get('/json', { method: 'GET', // mode:'cors', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, }).then(function (res) { if(res.status === 200){ return res.data } }).then(function (json) { //console.log(typeof Array.from(json), Array.from(json)); context.commit('setJson', Array.from(json)); }) } };

3、又会遇到跨域,在webpack中修改,路径config/index.js文件中添加proxyTable项的配置:

proxyTable: { '/json': { target: 'http://127.0.0.1:3000', changeOrigin: true, pathRewrite: { '^/json': '/json' } } },

后记

基于vue脚手架搭建的项目,模拟异步取数据,也可以直接在脚手架生成的static文件夹下放置数据,假装是后台拿过来的数据。

不过搭建一个基于express或者koa的web服务,确实也该是一个前端工程师应该掌握的。

OK,以上就是全文了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/pppzs.html