前后端分離之mockjs實戰demo


基於vue-cli+webpack的demo
項目結構


axios文件夾用來創建axios相關配置:

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

mock文件夾建立mock數據,配置mock請求:

// 引入mockjs
const Mock = require('mockjs');
// 獲取 mock.Random 對象
const Random = Mock.Random;
// mock一組數據
const produceNewsData = function() {
    let articles = [];
    for (let i = 0; i < 10; 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.date()指示生成的日期字符串的格式,默認為yyyy-MM-dd;
        }
        articles.push(newArticleObject)
    }
 
    return {
        articles: articles
    }
}
 
// Mock.mock( url, post/get , 返回的數據);
Mock.mock('/news/index', 'post', produceNewsData);

HelloWorld.vue頁面首頁:

<template>
  <div class="index">
    <div v-for="(item, key) in newsListShow" :key="key">
      <news-cell
      :newsDate="item"
      ></news-cell>
    </div>
  </div>
</template>
 
<script>
import api from 'js/axios/config'
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>

</style>

NewsCell.vue組件渲染數據:

<template>
  <div class="wrap">
    <div class="wrap-top">
      <h1>{{newsDate.title}}</h1>
      <span class="date">{{newsDate.date}}</span>
    </div>
    <div class="wrap-bottom">
      <span class="name">{{newsDate.author_name}}</span>
      <img :src="newsDate.thumbnail_pic_s" alt="">
    </div>
  </div>
</template>
 
<script>
export default {
  name: 'NewsCell',
  props: {
    newsDate: Object
  },
  data () {
    return {
    }
  },
  computed: {
  },
  methods: {
    jumpPage: function () {
      window.location.href = this.newsDate.url
    }
  }
}
</script>
 
<style scoped>
  .wrap{
    width: 100%;
    font-size: 0.3rem;
  }
  .wrap-top,.wrap-bottom{
    display: flex;
    align-items: center;
    justify-content:space-between;
  }
  h1{
    width: 6rem;
    text-align: left;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .date{
    width: 4rem;
  }
  .name{
    flex: 1;
  }
  img{
    width: 10rem;
  }
</style>

main.js入口文件:

// 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'
// 引入mockjs
require('js/mock/mock.js')
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

運行結果


更為詳細的介紹:
Mock.js簡易教程,脫離后端獨立開發,實現增刪改查功能


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM