当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue+mockjs模拟数据实现前后端分离开发的实例代码

vue+mockjs模拟数据实现前后端分离开发的实例代码

2017年12月12日  | 移动技术网IT编程  | 我要评论

鸿泰信htxvip,24k99黄金宝,神风神龙

本文介绍了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<br>cd mockjs<br>npm install axios --save 

3.安装mockjs

npm install mockjs --save-dev 

4.项目目录

axios/api    用来封装axios

hello.vue     页面首页

neswcell.vue   新闻组件

router/index.js   路由

main.js      入口js

mock.js     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" 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>

 

<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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网