Axios和Mockjs,玩起~~~

时间:2021-06-11 18:00:24

 

 

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‘: ‘[email protected],
    ‘order|1-20‘: 5,
})

Axios和Mockjs,玩起~~~