【vue2.0-数据请求步骤以及使用】

vue2.0-数据请求步骤以及使用

测试接口:postman--------https://www.postman.com/

1.二次封装axios
在src文件下创建api文件夹 request.js

// -request.js
import axios from 'axios'
//1.利用axios对象的方法create,去创建一个axios实际
//2.request就是axios,只不过稍微配置一下
const requests = axios.create({
    //配置对象
    //基础路径,发请求的时候,路径当中出现api
    baseURL:"/api",
    //代表请求超时的时间5s
    timeout:500,
})

//请求拦截器:在发请发之前,请求拦截器可以检测到,可以在请求发出去之前做一些事情
 requests.interceptors.request.use((config)=>{
     //config:配置对象,对象里面有一个属性很重要,headers请求
     return config
 })
//响应拦截器
requests.interceptors.response.use((res)=>{
    return res.data
},(error)=>{
    return Promise.reject(new Error('faile'))
})
export default axios

2.api统一管理
在api文件夹下创建index.js文件

//index.js
import requests from './request'
//例如
//三级联动接口
//接口地址  请求方式  有无参数 ----注释
//——get 无参
export const reqCategoryList = ()=> requests({url:'不带/api',method:'get'}))
//——post 有参
//params至少是一个空对象
export const reqGetSearchInfo = (params)=> requests({url:'不带/api',method:'post',data:params}))


//用的地方调用:
import {reqCategoryList} from '@/api'
reqCategoryList()

【vue2.0-数据请求步骤以及使用】_第1张图片
【vue2.0-数据请求步骤以及使用】_第2张图片
【vue2.0-数据请求步骤以及使用】_第3张图片

4.解决跨域

//vue.config.js
moudule.exports = {
   //关闭eslint
   lintOnSave:false,
   //代理路径
   devServer:{
       proxy:{
           '/api':{
               target:'地址',
               //pathRewrite:{'^/api':''}//重写地址:因为后面都是接着api所以不需要写
           }
       }
   }
}

5.进度条nprogress

    //在axios封装文件中使用 request.js
    import nprogress from 'nprogress'
    import 'nprogress/nprogress.css'
    //start 进度条开始  done 进度条结束
    requests.interceptors.request.use((config)=>{
        nprogress.start()
        return config
    })
    //响应拦截器
    requests.interceptors.response.use((res)=>{
        nprogress.done()
        return res.data
    },(error)=>{
        return Promise.reject(new Error('faile'))
    })

6.store中使用数据

const state={
    categoryList:[],
    saerchList:{}
}
const mutations={
   //2.名字要与actions的对应
    CATEGORYLIST(state,categoryList){
        state.categoryList = categoryList
    },
    GETSEARCHLIST(state,saerchList){
        state.saerchList = saerchList
    }
}
const actions={
 //1.async与await要一起用必须存在
 //      这个名字自定义
	 async categoryList({commit}){
     	let result = await reqCategoryList()
	     if(result.code==200){
	         commit('CATEGORYLIST',result.data)
	         //         commit给mutation
	     }
	 },
	 async getSearchList({commit},params={}){
       //params形参:是当用户派发actions这个函数在调用获取服务器数据的时候,至少传递一个参数(空对象)
       let result = await reqCategoryList(params)
       if(result.code==200){
           commit('GETSEARCHLIST',result.data)
           //         commit给mutation
       }
   	}
 },
//在项目中getters主要作用是;简化数据而生
const getters={
    //当前形参state,当前仓库中的state,并非大仓库中的state
    goodsList(state){
        //state.searchList.goodsList如果服务器数据回来了,没问题是一个数组
        //加入网络不给力|没有网
        return state.searchList.goodsList|| []
    }
}
export default {
     state,
     mutations,
     actions,
     getters
 }

需要写的效果展示

import {mapState,mapGetters} from 'vuex'//获取state+getters
   export default {
   name: "TypeNav",
   data:{
       searchParams:{
           categeory1Id:"",
           categeory2Id:"",
           categeory3Id:"",
           categoryName:"",
           keyword:"",
           order:"",
           pageNo:1,
           pageSize:10,
           props:[],
           trademark:"",
       }
   },
   
   beforeMounte(){
    //再发请求之前,把接口需要传递的参数进行整理(再给服务器请求之前把参数整理好,服务器就会返回查询的数据)
   Object.assign(this.searchParams,this.$route.query,this.$route.params)
   }
   
   methods:{
       //向服务器发请求获取search模块数据(根据参数不同返回不同的数据进行展示)
       getData(){
           
           this.$store.dispatch('getSearchList',this.searchParams)
       }
   },
   
   mounted() {
       //通知vuex发送请求,获取数据,存储于仓库当中
       this.$store.dispatch('categoryList')
       this.getData()   
   },

   //*dispatch和计算属性这俩缺一不可
   //dispatch是发送请求
   // 计算属性是将其赋值
   computed:{
        ...mapState({
            //由于在这里categoryList对象赋值了 所以在页面中可以直接使用categoryList
            categoryList:state=>state.home.categoryList
            <!--
                <div v-if="categoryList"></div>
            -->
        }),
        //mapgetters里面的写法:传递的数组,因为getters计算是没有划分模块[home,search]
        ...mapGetters(['goodsList'])
    };

你可能感兴趣的:(前端框架搭建,vue)