json-server 快速伪造后台接口
使用 Vue 也有一段时间了,现在对 Vue 的一些以前没有注意到的点小结一番~
本文均采用 npm 安装依赖
json-server
数据存储的利器啊,我之前是采用 easy-mock,遗憾的是其只能使用 get 请求。在 json-server 中,我们采用 npm install -g json-server
安装依赖。在最外层文件新建 mock 文件,下建 db.json,然后采用 json 格式输入数据。
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
然后改改 script,在 package.json
中,修改 script
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "node build/dev-server.js",
"build": "node build/build.js",
"mock": "json-server mock/db.json --port 9092",
"mockdev": "npm run mock & npm run dev"
},
你可以用 npm run dev
打开项目 npm run mock
打开json-server,npm run mockdev
两个一起打开~~,在 localhost9092 可以看到我们的 mock 数据,端口地址可以在 port
后面改,要对数据进行操作,需设置我们的基地址
let baseUrl = 'http://localhost:9092';
配合 axios 使用,即可对数据进行增删改查
import axios from'axios'
export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
type = type.toUpperCase();
url = baseUrl + url;
if (type == 'GET') { // searchtry {
var res = await axios.get(url)
return res
} catch (error) {
console.error(error)
}
} elseif(type == 'PUT') { // edittry {
await axios.put(url,data.data)
} catch (error) {
console.error(error)
}
} elseif(type == 'POST') { // addtry {
await axios.post(url,data.data)
} catch (error) {
console.error(error)
}
} elseif(type == 'DELETE') { // deletetry {
await axios.delete(url,data.data)
} catch (error) {
console.error(error)
}
}
}
比如我们要对数据中的 posts 进行 get 操作,只需在基地址后加上 /posts
,而若是要对其中的 id为1
的进行操作,则在基地址后加上 /posts/1
vuex
使用 vuex 的时候参照了 github 的 vue大项目 elm,觉得这种数据分离的方式特别好,推荐给大家
首先安装依赖 npm install vuex --save
新建文件夹 store,下建 index.js
和 mutation.js
,这里我只建了 mutation.js
,原版还有 getter.js
和 action.js
,但因为项目中没用到,故没有建。
index.js
import Vue from'vue'
import Vuex from'vuex'
import mutations from'./mutations'
Vue.use(Vuex)
const state = {
example: ''
}
exportdefaultnew Vuex.Store({
state,
mutations
})
mutation.js
exportdefault {
setExample (state, newData) {
state.example = newData
}
}
从而在我们的工程文件中,引入相应的函数传入相应的数据即可
helloWorld.vue
...mapMutations([
'setExample'
]),
async initData(){ // 异步大法好
let res = await getData();
this.setExample(res.data)
this.data = res.data;
},
service/getData.js
import fetch from'../config/fetch'exportconst getData = () => fetch('/posts', {});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论