美文网首页
Vue3.0商店后台管理系统项目实战-axios的封装

Vue3.0商店后台管理系统项目实战-axios的封装

作者: 祈澈菇凉 | 来源:发表于2022-10-18 09:43 被阅读0次

    参考资料

    Vue3.0官方文档:https://cn.vuejs.org/
    Element Plus文档:https://element-plus.gitee.io/zh-CN/

    在项目里面安装

    npm i axios -S

    封装一个axios
    在文件里面新建一个util/service.js


    import { ElLoading } from 'element-plus'
    import { ElMessage } from 'element-plus'
    
    
    import axios from "axios"
    //使用create 创建axios实例
    
    let loadingObj=null
    
    const Service=axios.create({
        timeout:8000,
        baseURL:"http://xx",
        headers:{
            "Content-type":"application/json;charset=utf-8"
        }
        
    })
    //请求拦截-增加loading,对请求进行统一的处理
    Service.interceptors.request.use(config=>{
        loadingObj=ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
          })
    
          return config
    })
    
    //响应拦截--对返回值做统一处理
    Service.interceptors.response.use(response=>{
        return response.data
    },err=>{
        loadingObj.close()
        ElMessage({
            message:"服务器错误",
            type:"error",
            duration:2000
    
        })
    })
    
    //post请求
    export const post=config=>{
        return Service({
            ...config,
            method:"post",
            data:config.data
        })
    }
    
    
    //get请求
    export const get=config=>{
        return Service({
            ...config,
            method:"get",
            data:config.data
        })
    }
    
    

    新建一个request.js


    request.js

    import {post,get} from "./service"
    export const  loginApi=data=>{
        return post({
            url:"./login",
            data
        })
    }
    

    在login.vue里面引入request

    在实际项目里面 封装使用
    service.js

    import axios from "axios"
    
    import { ElLoading } from 'element-plus'
    import { ElMessage } from 'element-plus'
    // //使用create 创建axios实例
    
    // let loadingObj=null
    
    // const Service=axios.create({
    //     timeout:8000,
    //     baseURL:"http://192.168.16.103:8091/chem/login",
    //     headers:{
    //         "Content-type":"application/json;charset=utf-8"
    //     }
        
    // })
    
    // 使用create创建axios实例
    let loadingObj = null
    const Service = axios.create({
        timeout:8000,
        baseURL:"http://47.100.36.235:8091/check/login",
        headers:{
            "Content-type":"application/json;charset=utf-8",
          //  "Authorization":store.state.uInfo.userInfo.token
        }
    })
    
    // 请求拦截-增加loading,对请求做统一处理
    Service.interceptors.request.use(config=>{
        loadingObj=ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        return config
    })
    // 响应拦截-对返回值做统一处理
    Service.interceptors.response.use(response=>{
        loadingObj.close()
        const data = response.data
        if(data.meta.status!=200 && data.meta.status!=201){
            ElMessage.error(data.meta.msg||"服务器出错")
            // 请求出错 
            return data
        }
        return data
    
    },error=>{
        loadingObj.close()
        ElMessage({
            message:"服务器错误",
            type:"error",
            duration:2000
        })
    })
    
    // post请求
    export const post=config=>{
        return Service({
            ...config,
            method:"post",
            data:config.data
        })
    }
    // get请求
    export const get=config=>{
        return Service({
            ...config,
            method:"get",
            params:config.data
        })
    }
    

    request.js

    import {post,get} from "./service"
    export const loginApi=data=>{ 
        return post({
            url:"/login",
            data
        })
    }
    

    login.vue

    <template>
      <div class="login_wrap">
        <div class="form_wrap">
          <el-form
            ref="formRef"
            :model="loginData"
            label-width="100px"
            class="demo-dynamic"
          >
            <el-form-item
              prop="username"
              label="用户名"
              :rules="[
                {
                  required: true,
                  message: '此项为必填项',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input v-model="loginData.username" />
            </el-form-item>
    
            <el-form-item
              prop="password"
              label="密码"
              :rules="[
                {
                  required: true,
                  message: '此项为必填项',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input type="password" v-model="loginData.password" />
            </el-form-item>
    
            <el-form-item>
              <el-button type="primary" @click="handleLogin()">登录</el-button>
            
            </el-form-item>
          </el-form>
        </div>
      </div>
    </template>
    
    <script>
    import { reactive, toRefs } from "vue";
    
    //引入useStore
    import { useStore } from "vuex";
    //引入路由
    import { useRouter } from "vue-router";
    
    //import {loginApi} from "@util/request"
    import {loginApi} from "@/util/request"
    
    export default {
      name: "login",
      setup() {
        const store = useStore();
        const router = useRouter();
    
        const count = store.state.number.count;
    
        const data = reactive({
          loginData: {
            username: "",
            password: "",
          },
          num: count,
          // countStatus:
        });
    
        const handleLogin = () => {
          //请求后台接口
          loginApi(data.loginData).then(res=>{
            console.log("登录的返回",res)
    
            if(res.data){
                        store.commit('setUserInfo', res.data);
                        localStorage.setItem("loginData",JSON.stringify(res.data))
                        // 跳转/user
                        router.push({
                            path:"/"
                        })
                    }
                    
          })
          // store.commit("setUserInfo", data.loginData);
          // localStorage.setItem("loginData",JSON.stringify(data.loginData))
          
          // //跳转user页面
          // router.push({
          //   path:"/user"
          // })
        };
    
        // console.log("修改前getters", store.getters["number/countStatus"]);
        // const handleLogin = () => {
    
        //   store
        //     .dispatch("number/setCountPromise", -100)
        //     .then((res) => {
        //       alert("修改成功");
        //     })
        //     .catch((err) => {
        //       alert(err);
        //     });
        //   console.log(store.state.number.count);
        //   console.log("修改后getters",store.getters["number/countStatus"]);
        // };
        return {
          ...toRefs(data),
          handleLogin,
        };
      },
    };
    </script>
    <style scoped>
    .login_wrap {
      width: 100%;
      height: 100vh;
      background: #2d3761;
      position: relative;
    }
    .form_wrap {
      position: fixed;
      top: 50%;
      transform: translate(130%, -50%);
      background: #fff;
      padding: 30px 50px;
      border-radius: 5px;
    }
    </style>
    

    相关文章

      网友评论

          本文标题:Vue3.0商店后台管理系统项目实战-axios的封装

          本文链接:https://www.haomeiwen.com/subject/uxntzrtx.html