vue---mock模拟数据与三大数据请求方式

一、mock模拟数据

  1. 安装
cnpm install mockjs --save-dev
  1. 建立mock.js文件,并在该文件中引入mock
import Mock from "mockjs";

3.在main.js文件中引入mock.js文件

import Mock from "./mock/mock"   //"./mock/mock"  为mock.js文件路径

4.在mock.js文件中使用mock方法模拟数据

mock()方法的三个参数
参数一:自定义路径
参数二:获取数据的方式  get/post
参数三:模拟的数据

以下为模拟数据的两种方法:

  • 以回调函数的方法模拟数据
Mock.mock("/getuser","get",()=>{
    return {
        result:[
            {
                "id":1,
                "name":"张三",
                "sex":"男"
            } ]
 }});

  • 以对象的方式模拟数据
Mock.mock("/getdata","post",{
    result:[
        {
            "name":"张三",
            "sex":"男"
        }]
})

二、获取数据的三种方式

1.vue-resource请求

  • 安装和配置
    1.安装  cnpm install vue-resource
    2.在main.js中配置
      2.1  引入vue-resource
      import Vueresource  from 'vue-resource';    //Vueresource  为自定义变量名
      2.2  给Vue使用
      Vue.use(Vueresource);
  • 获取数据的方法
//this.$http.get("要获取数据的路径")  或  this.$http.post("要获取数据的路径")  
this.$http.get("/getuser").then(res=>{
    console.log(res);   //获得的数据
 }).catch(error=>{
     console.log(error);   //请求失败返回的错误
 });

2.axios请求

  • 安装
 cnpm install --save-dev axios
  • 引入与使用:分为在单个组件使用和全局使用
    以下为在单个组件中引入及其使用
//引入
import Axios from "axios";
//Axios.post("要获取数据的路径")  或Axios.get("要获取数据的路径")    
Axios.post("/getdata").then(res=>{
    console.log(res.data.result);
    this.axiosdata=res.data.result;
}).catch(error=>{
    console.log(error); 
});

以下为全局引入和其使用

//在main.js中   全局引入 axios
import Axios from "axios";
//将 axios绑定到vue的全局对象上 
Vue.prototype.$axios=Axios;
//在所有组件中的使用方法
this.$axios.get()  /  this.$axios.post()

  • async函数写法

使用 await 需要相关安装和配置

1.安装 cnpm install --save-dev babel-plugin-transform-run
2..babelrc 文件中配置
 "plugins":["transform-runtime"]

使用 async函数获取

 async function  method(){
        let user=await Axios.get("/getuser");
        return user;
 }
method().then(res=>{
    console.log(res.data.result);
    }).catch(error=>{
        console.log(error);
    });

也可直接在async函数体内捕获异常

 async function  method(){
    try{
      let user=await Axios.get("/getuser");
      return user;
    }
    catch(e){
      throw(e);
    }
 }
  • axios向后台数据传参问题(mock无法模拟后台接收参数)

    get方式 向后台传参

   //方法一  Axios.get("url");  直接传路径     
    Axios.get("http://www.enheng.com/getdata?id=0299&name=enheng");

   //方法二: 利用params传参
      Axios.get("/getuser",{
           params:{
               "id":"0299",
               "name":"enheng"
           }
       }).then(res=>{
           console.log(res);
       }).catch(error=>{
           console.log(error); 
       });

post方式 向后台传参

    //直接以对象的方式传参
     Axios.get("/getuser",{
               "id":"0299",
                name:"enheng"
       }).then(res=>{
           console.log(res);
       }).catch(error=>{
           console.log(error); 
       });

3.fetch-jsonp请求

  • 安装
 cnpm install --save-dev fetch-jsonp
  • 引入与使用:分为在单个组件使用和全局使用
    以下为在单个组件中引入及其使用
//引入
import Fetchjsonp  from "fetch-jsonp"
//使用  以百度关键字搜索接口为例
 let src = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=1";
       Fetchjsonp(src,{
           jsonpCallback: "cb", //指定回调函数的参数
           jsonpCallbackFunction: "getData", //指定回调函数的函数名称
           timeout:2000    //请求时间
        }).then(response=>{
           console.log(response);
           //{ok: true, json: ƒ}
           return response.json();
       }).then(json=>{
           //请求成功返回的数据
          console.log(json.s);   
       }).catch(ex=>{
           //请求失败返回的错误
           console.log(ex);
       });

以下为全局引入和其使用

//在main.js中 全局引入 fetch-json
import Fetch  from "fetch-jsonp";
//配置 将 axios绑定到vue的全局对象上 
Vue.prototype.$fetch=Fetch;
//在所有组件中使用方法 
this.$fetch("")
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要去除vue-element-admin中的mock功能,可以按照以下步骤进行操作: 1. 打开项目的根目录,并找到.env.development文件。 2. 在.env.development文件中,找到以下代码,并将其注释掉: ``` // if (process.env.NODE_ENV === 'production') { // const { mockXHR } = require('../mock') // mockXHR() // } ``` 3. 保存并关闭.env.development文件。 4. 打开项目的src/main.js文件。 5. 在main.js文件中,找到以下代码,并将其注释掉: ``` // import { mockXHR } from '../mock' // if (process.env.NODE_ENV === 'production') { // mockXHR() // } ``` 6. 保存并关闭main.js文件。 经过以上步骤,你已成功去除了vue-element-admin中的mock功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [vue-element-admin 去掉mock数据,用后台接口登录](https://blog.csdn.net/weixin_45835850/article/details/116228701)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [vue-element-admin v4.x入门 & 去除mock请求自己接口 & 跨域问题](https://blog.csdn.net/weiiscomeon/article/details/96695526)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [vue3-element-admin:vue3-element-admin后台管理系统前端解决方案](https://download.csdn.net/download/weixin_42135754/16733756)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值