vue+mockjs 模擬真實數據 axios

{
  // `data` 由服務器提供的響應
  data: {},

  // `status`  HTTP 狀態碼
  status: 200,

  // `statusText` 來自服務器響應的 HTTP 狀態信息
  statusText: "OK",

  // `headers` 服務器響應的頭
  headers: {},

  // `config` 是爲請求提供的配置信息
  config: {}
}

<body>
<div id="app">
  <h1>網站列表</h1>
  <div
    v-for="site in info"
  >
    {{ site.name }}
  </div>
</div>
<script type = "text/javascript">
new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://www.runoob.com/try/ajax/json_demo.json')
      .then(response => (this.info = response.data.sites))
      .catch(function (error) { // 請求失敗處理
        console.log(error);
      });
  }
})
</script>
</body>
</html>
{
    "data": {
        "name": "網站",
        "num": 3,
        "sites": [
            {
                "name": "Google",
                "info": [
                    "Android",
                    "Google 搜索",
                    "Google 翻譯"
                ]
            },
            {
                "name": "Runoob",
                "info": [
                    "菜鳥教程",
                    "菜鳥工具",
                    "菜鳥微信"
                ]
            },
            {
                "name": "Taobao",
                "info": [
                    "淘寶",
                    "網購"
                ]
            }
        ]
    },
    "status": 200,
    "statusText": "",
    "headers": {
        "accept-ranges": "bytes",
        "age": "96850",
        "ali-swift-global-savetime": "1585128839",
        "cache-control": "s-maxage=163749, max-age=163749",
        "content-length": "291",
        "content-type": "application/json",
        "date": "Tue, 23 Jun 2020 03:51:34 GMT",
        "eagleid": "793f8d1e15929811442472602e",
        "etag": "\"5ce7cb1c-123\"",
        "expires": "Thu, 25 Jun 2020 01:20:43 GMT",
        "last-modified": "Fri, 24 May 2019 10:44:44 GMT",
        "server": "Tengine",
        "status": "304",
        "timing-allow-origin": "*",
        "via": "cache37.l2cn1837[0,304-0,H], cache68.l2cn1837[0,0], cache2.cn284[0,304-0,H], cache10.cn284[0,0]",
        "x-cache": "HIT TCP_IMS_HIT dirn:13:391583864",
        "x-swift-cachetime": "86400",
        "x-swift-savetime": "Wed, 24 Jun 2020 01:20:43 GMT"
    },
    "config": {
        "transformRequest": {},
        "transformResponse": {},
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "headers": {
            "Accept": "application/json, text/plain, */*"
        },
        "method": "get",
        "url": "https://www.runoob.com/try/ajax/json_demo.json"
    },
    "request": {}
}
  1. 前-後端分離;
  2. 不需要修改既有代碼,就可以攔截 Ajax 請求,返回模擬的響應數據;
  3. 數據類型豐富;
  4. 通過隨機數據,模擬各種場景;
npm install --global vue-cli

創建vue項目

vue init webpack mockjs<br>cd mockjs<br>npm install axios --save

安裝mockjs

npm install mockjs --save-dev

在這裏插入圖片描述

axios/api    用來封裝axios
Hello.vue     頁面首頁
NeswCell.vue   新聞組件
router/index.js   路由
main.js      入口js
mock.js     mockjs文件

在這裏插入圖片描述
在入口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.

//1.引入組件 import Vue from 'vue'
//2. 引入app.vue用它的內容來替換div id = app import App from './App'
//3. 構建vue實例


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];
})

添加一個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);

hello.vue中接收mockjs數據

<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.js中封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);
  }
}

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

路由

import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello
    }
  ]
})

代碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章