當前位置:
首頁 > 知識 > vue+mockjs 模擬數據,實現前後端分離開發

vue+mockjs 模擬數據,實現前後端分離開發

在項目中嘗試了mockjs,mock數據,實現前後端分離開發。

關於mockjs,官網描述的是

1.前後端分離

2.不需要修改既有代碼,就可以攔截 Ajax 請求,返回模擬的響應數據。

3.數據類型豐富

4.通過隨機數據,模擬各種場景。

等等優點。

總結起來就是在後端介面沒有開發完成之前,前端可以用已有的介面文檔,在真實的請求上攔截ajax,並根據mockjs的mock數據的規則,模擬真實介面返回的數據,並將隨機的模擬數據返回參與相應的數據交互處理,這樣真正實現了前後台的分離開發。

與以往的自己模擬的假數據不同,mockjs可以帶給我們的是:在後台介面未開發完成之前模擬數據,並返回,完成前台的交互;在後台數據完成之後,你所做的只是去掉mockjs:停止攔截真實的ajax,僅此而已。

下面一步步的來實現vue-cli創建項目並添加一條新聞類的數據模擬介面:

1.安裝vue-cli全局腳手架

npm install --global vue-cli

2.創建vue項目

vue init webpack mockjs
cd mockjs
npm install axios --save

3.安裝mockjs

npm install mockjs --save-dev

4.項目目錄

vue+mockjs 模擬數據,實現前後端分離開發

axios/api 用來封裝axios

Hello.vue 頁面首頁

NeswCell.vue 新聞組件

router/index.js 路由

main.js 入口js

mock.js mockjs文件

在來看下完成後的效果

vue+mockjs 模擬數據,實現前後端分離開發

5.在入口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

6. 添加一個mock規則(mock.js)

// 引入mockjs
const Mock = require("mockjs");
// 獲取 mock.Random 對象
const Random = Mock.Random;
// mock一組數據
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指示生成的日期字元串的格式,默認為yyyy-MM-dd;Random.time 返回一個隨機的時間字元串
}
articles.push(newArticleObject)
}

return {
articles: articles
}
}

// Mock.mock( url, post/get , 返回的數據);
Mock.mock("/news/index", "post", produceNewsData);

7.在Hello.vue 中請求文檔介面,並接收mock數據

<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>

注意:api.JH_news是我封裝的axios函數

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);
})
// 響應攔截器
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展示數據

<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" stylex="width:0.24rem;height:0.2rem;">
<span class="fl">{{newsDate.author_name}}</span>
</section>
<section class="Cright">
<img src="./../assets/icon/clock.png" stylex="width:0.2rem;height:0.2rem;">
<span>{{newsDate.date | getYMD}}</span>
</section>
<div stylex="clear: both"></div>
</aside>
<aside>
<img :src="newsDate.thumbnail_pic_s" stylex="border-radius: 0.2rem;">
</aside>
<div stylex="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>

<style scoped>
.financial-list {
width: 100%;
height: 100%;
background-color: white;
padding: 0.28rem 0;
border-bottom: 1px solid #ccc;
}

.financial-list .collect {
width: 92%;
margin: 0 auto;
}

.financial-list .collect aside:nth-of-type(1) {
width: 63%;
float: left;
}

.financial-list .collect aside:nth-of-type(2) {
width: 32%;
height: 2rem;
float: left;
margin-left: 0.3rem;
}

.financial-list .collect h2 {
width: 100%;
height: 0.96rem;
font-size: 0.32rem;
color: #333333;
line-height: 0.48rem;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
overflow: hidden;
}

.financial-list .collect aside:nth-of-type(2) img {
width: 100%;
height: 100%;
}

.financial-list .collect aside .Cleft {
width: 45%;
float: left;
margin-top: 0.66rem;
}

.financial-list .collect aside .Cleft span{
display: block;
width: 1.4rem;
margin-left: 0.05rem;
white-space: nowrap;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
overflow: hidden;
}

.financial-list .collect aside .Cright {
width: 55%;
float: right;
margin-top: 0.66rem;
}
.financial-list .collect aside .Cright span{
display: inline-block;
margin: 0.04rem 0 0 0.05rem;
}
.financial-list .collect aside span {
font-size: 0.2rem;
color: #999999;
}

.financial-list .collect aside .Cleft img,
.financial-list .collect aside .Cright img {
width: 0.18rem;
height: 0.24rem;
margin-top: 0.09rem;
}
</style>

完成

9.所有代碼可以查看我的github: https://github.com/Jasonwang911/vue_mockjs

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 達人科技 的精彩文章:

ReactiveSwift源碼解析(十)Lifetime代碼實現
一份關於webpack2和模塊打包的新手指南
Openresty使用Thrift安裝步驟

TAG:達人科技 |

您可能感興趣

jacoco與jenkins集成實現代碼覆蓋率分析
spring+mybatis 實現多數據源切換
在Spark 上實現 TensorFlow 的庫——Sparkflow
Python + Memcached: 在分散式應用程序中實現高效緩存
python 實現redis訂閱發布功能
Python + Memcached:在分散式應用程序中實現高效緩存
Virgil Abloh 主導下的 Louis Vuitton x Nike,在他們手中早就實現了…
PS4終於實現了Fortnite cross-play功能
Google發布Cloud AutoML,「點擊一下,為所有人實現AI」
Socket.io+canvas實現實時繪畫
用Pytorch 實現的 Capsule Network
通過Html2canvas實現截屏
用 greenlet 實現 Python 中的並發
實現高速點擊的 Android Monkey 自動化工具 fastmonkey-代號 Maxim
Yaw VR登陸Kickstarter,可實現3DoF追蹤
js和canvas實現旋轉圖片
5.使用dynamic_reconfigure實現節點參數動態更新
nginx+rtmp+livePush實現視頻轉流推流
Python+Memcached:在分散式應用程序中實現高效緩存
實現一份數據的夢想,Apache CarbonData里程碑式版本1.3發布