Axios和Mockjs,玩起~~~

Posted aguncn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Axios和Mockjs,玩起~~~相关的知识,希望对你有一定的参考价值。

 

 

router/index.js

import Vue from ‘vue‘
import VueRouter from ‘vue-router‘
import Home from ‘@/views/Home.vue‘
import Login from ‘@/views/Login.vue‘
import About from ‘@/views/About.vue‘
import NotFound from ‘@/views/404.vue‘

Vue.use(VueRouter)

const routes = [
  {
    path: ‘/‘,
    name: ‘home‘,
    component: Home
  },
  {
    path: ‘/about‘,
    name: ‘about‘,
    component: About
  },
  {
    path: ‘/login‘,
    name: ‘login‘,
    component: Login
  },
  {
    path: ‘/404‘,
    name: ‘notFound‘,
    component: NotFound
  }

]

const router = new VueRouter({
  mode: ‘history‘,
  base: process.env.BASE_URL,
  routes
})

export default router

views/about.vue

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <el-button type="primary" @click="testAxios()">Test Axios</el-button>
    <el-button type="primary" @click="getUser()">UserInfo</el-button>
    <el-button type="primary" @click="getMenu()">Menu</el-button>
  </div>
</template>

<script>
import axios from ‘axios‘
import mock from ‘@/mock/mock.js‘
export default {
    name: "about",
    methods: {
        testAxios() {
            axios.get(‘http://127.0.0.1:8080/‘).then(res => { alert(res.data) })
        },
        getUser() {
            axios.get(‘http://127.0.0.1:8080/user‘).then(res => { alert(JSON.stringify(res.data)) })
        },
        getMenu() {
            axios.get(‘http://127.0.0.1:8080/menu‘).then(res => { alert(JSON.stringify(res.data)) })
        },
    }
}
</script>

mock/mock.js

import Mock from ‘mockjs‘

Mock.mock(‘http://127.0.0.1:8080/user‘, {
    ‘name‘: ‘@name‘,
    ‘email‘: ‘@email‘,
    ‘age|1-10‘: 5,
})

Mock.mock(‘http://127.0.0.1:8080/menu‘, {
    ‘id‘: ‘@increment‘,
    ‘name‘: ‘menu@increment‘,
    ‘order|1-20‘: 5,
})

技术图片

以上是关于Axios和Mockjs,玩起~~~的主要内容,如果未能解决你的问题,请参考以下文章

axios拦截器+mockjs

MockjsReact + Mockjs 模拟接口

MockjsReact + Mockjs 模拟接口

前后端分离之mockjs实战demo

Vue开发实例(13)之axios和mockjs的安装与使用

Vue开发实例(13)之axios和mockjs的安装与使用