在項目中嘗試了mockjs允耿,mock數(shù)據(jù)典蝌,實現(xiàn)前后端分離開發(fā)单料。
關(guān)于mockjs,官網(wǎng)描述的是
1.前后端分離
2.不需要修改既有代碼锅减,就可以攔截 Ajax 請求,返回模擬的響應(yīng)數(shù)據(jù)伐坏。
3.數(shù)據(jù)類型豐富
4.通過隨機數(shù)據(jù)怔匣,模擬各種場景。等等優(yōu)點桦沉。
總結(jié)起來就是在后端接口沒有開發(fā)完成之前每瞒,前端可以用已有的接口文檔,在真實的請求上攔截ajax纯露,并根據(jù)mockjs的mock數(shù)據(jù)的規(guī)則剿骨,模擬真實接口返回的數(shù)據(jù),并將隨機的模擬數(shù)據(jù)返回參與相應(yīng)的數(shù)據(jù)交互處理埠褪,這樣真正實現(xiàn)了前后臺的分離開發(fā)浓利。
與以往的自己模擬的假數(shù)據(jù)不同挤庇,mockjs可以帶給我們的是:在后臺接口未開發(fā)完成之前模擬數(shù)據(jù),并返回荞膘,完成前臺的交互罚随;在后臺數(shù)據(jù)完成之后,你所做的只是去掉mockjs:停止攔截真實的ajax羽资,僅此而已淘菩。
下面一步步的來實現(xiàn)vue-cli創(chuàng)建項目并添加一條新聞類的數(shù)據(jù)模擬接口:
- 安裝vue-cli全局腳手架
npm install --global vue-cli
- 創(chuàng)建vue項目
vue init webpack mockjs<br>cd mockjs<br>npm install axios --save
3.安裝mockjs
npm install mockjs --save-dev
- 項目目錄
mokejs文件里面包含src build router app.vue main.js 等文件 main.js下面還有個moke.js
axios/api 用來封裝axios
Hello.vue 頁面首頁
NeswCell.vue 新聞組件
router/index.js 路由
main.js 入口js
mock.js mockjs文件
完成后的數(shù)據(jù)已經(jīng)渲染
- 在入口js(main.js)里引入mockjs
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
// 引入mockjs
require('./mock.js')
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: {
App
}
})
Vue.filter('getYMD', function(input) {
return input.split(' ')[0];
})
這里添加了額一個常用的時間整理過濾器 getYMD
- 添加一個mock規(guī)則(mock.js)
// 引入mockjs
const Mock = require('mockjs');
// 獲取 mock.Random 對象
const Random = Mock.Random;
// mock一組數(shù)據(jù)
const produceNewsData = function() {
let articles = [];
for (let i = 0; i < 100; i++) {
let newArticleObject = {
title: Random.csentence(5, 30), // Random.csentence( min, max )
thumbnail_pic_s: Random.dataImage('300x250', 'mock的圖片'), // Random.dataImage( size, text ) 生成一段隨機的 Base64 圖片編碼
author_name: Random.cname(), // Random.cname() 隨機生成一個常見的中文姓名
date: Random.date() + ' ' + Random.time() // Random.date()指示生成的日期字符串的格式,默認(rèn)為yyyy-MM-dd;Random.time() 返回一個隨機的時間字符串
}
articles.push(newArticleObject)
}
return {
articles: articles
}
}
// Mock.mock( url, post/get , 返回的數(shù)據(jù))屠升;
Mock.mock('/news/index', 'post', produceNewsData);
- 在Hello.vue 中請求文檔接口潮改,并接收mock數(shù)據(jù)
<template>
<div class="index">
<div v-for="(item, key) in newsListShow">
<news-cell
:newsDate="item"
:key="key"
></news-cell>
</div>
</div>
</template>
<script>
import api from './../axios/api.js'
import NewsCell from './NewsCell.vue'
export default {
name: 'index',
data () {
return {
newsListShow: [],
}
},
components: {
NewsCell
},
created() {
this.setNewsApi();
},
methods:{
setNewsApi: function() {
api.JH_news('/news/index', 'type=top&key=123456')
.then(res => {
console.log(res);
this.newsListShow = res.articles;
});
},
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.topNav{
width: 100%;
background: #ED4040;
position: fixed;
top:0rem;
left: 0;
z-index: 10;
}
.simpleNav{
width: 100%;
line-height: 1rem;
overflow: hidden;
overflow-x: auto;
text-align: center;
font-size: 0;
font-family: '微軟雅黑';
white-space: nowrap;
}
.simpleNav::-webkit-scrollbar{height:0px}
.simpleNavBar{
display: inline-block;
width: 1.2rem;
color:#fff;
font-size:0.3rem;
}
.navActive{
color: #000;
border-bottom: 0.05rem solid #000;
}
.placeholder{
width:100%;
height: 1rem;
}
</style>
ps: api.JH_news是封裝的axios函數(shù)
axios/api.js如下
import axios from 'axios'
import vue from 'vue'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// 請求攔截器
axios.interceptors.request.use(function(config) {
return config;
}, function(error) {
return Promise.reject(error);
})
// 響應(yīng)攔截器
axios.interceptors.response.use(function(response) {
return response;
}, function(error) {
return Promise.reject(error);
})
// 封裝axios的post請求
export function fetch(url, params) {
return new Promise((resolve, reject) => {
axios.post(url, params)
.then(response => {
resolve(response.data);
})
.catch((error) => {
reject(error);
})
})
}
export default {
JH_news(url, params) {
return fetch(url, params);
}
}
8.在NewsCell.vue展示數(shù)據(jù)
<template>
<section class="financial-list">
<section class="collect" @click="jumpPage">
<aside>
<h2>{{newsDate.title}}</h2>
<section class="Cleft clearfix">
<img class="fl" src="./../assets/icon/eyes.png" style="width:0.24rem;height:0.2rem;">
<span class="fl">{{newsDate.author_name}}</span>
</section>
<section class="Cright">
<img src="./../assets/icon/clock.png" style="width:0.2rem;height:0.2rem;">
<span>{{newsDate.date | getYMD}}</span>
</section>
<div style="clear: both"></div>
</aside>
<aside>
<img :src="newsDate.thumbnail_pic_s" style="border-radius: 0.2rem;">
</aside>
<div style="clear: both"></div>
</section>
</section>
</template>
<script>
export default {
name: 'NewsCell',
props: {
newsDate: Object
},
data () {
return {
}
},
computed: {
},
methods: {
jumpPage: function () {
window.location.href = this.newsDate.url
}
}
}
</script>
ps: 此文為摘抄 僅作為筆記方便以后閱讀