Vue3+Vite+Pinia+Naive后台管理系统搭建之六:Axios 网络请求

前言

如果对 vue3 的语法不熟悉的,可以移步Vue3.0 基础入门快速入门。

Axios 详情可移步官网参看:Axios 官网

github 开源库:Vue3-Vite-Pinia-Naive-Js

gitee   开源库:Vue3-Vite-Pinia-Naive-Js

1. 安装依赖

yarn add axios
// or
npm install axios

2. 新增 .env 环境配置

对环境配置不了解的可移步:Vue 入门系列:.env 环境变量

2.1 新增 .env.development 开发环境变量
# 开发环境配置
ENV = 'development'

# 开发环境
VITE_APP_BASE_API = '/dev-api'
 2.2 新增 .env.production 生产环境变量
# 生产环境配置
ENV = 'production'

# 生产环境
VITE_APP_BASE_API = '/prod-api'

 

3. 编辑 vite.config.js 中的 server

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

import { resolve } from "path";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": resolve(__dirname, "./src"),
    },
  },
  // 服务配置
  server: {
    // 是否开启https
    https: false,
    // 端口号
    port: 3000,
    // 监听所有地址
    host: "0.0.0.0",
    // 启服务自动打开浏览器
    open: false,
    // 允许跨域
    cors: true,
    proxy: {
      "/dev-api": {
        target: "http://xxx.x.xxx.xxx:8080",
        changeOrigin: true,
        ws: true,
        rewrite: (path) => path.replace(/^\/dev-api/, ""),
      },
      "/dev/file": {
        target: "http://xxx.x.xxx.xxx:9300",
        changeOrigin: true,
        ws: true,
        rewrite: (path) => path.replace(/^\/dev/, ""),
      },
    },
  },
});
4. 新增 src/api/http.js 配置 aixos 基础配置
import axios from "axios";

// 请求和响应的消息主体用什么方式编码
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000,
});

// 请求拦截器
service.interceptors.request.use((config) => {
  // TODO
  return config;
});

// 响应拦截器
service.interceptors.response.use((res) => {
  // TODO
  return res.data;
});

export default service;

5. 新增 src/api/login.js 接口封装

import api from "./http.js";

// 登录
export function login(data) {
  return api({
    url: "/login",
    method: 'post',
    data
  })
}

// 登出
export function logout() {
  return api({
    url: '/logout',
    method: 'delete'
  })
}

6. 编辑 src/pages/login.vue 组件中调用接口

<script setup>
import router from "@/router/index.js";
import { NButton } from "naive-ui";
import { login } from "@/api/login.js";

let handleLogin = () => {
  login().then(() => {
    router.push({ name: "home" });
  });
};
</script>

<template>
  <div class="login">
    <n-button type="primary" size="small" @click="handleLogin">登录</n-button>
  </div>
</template>

<style lang="scss" scoped></style>

 注意:vite.config.js 中环境映射不是真实的地址,所以请求失败,请根据自己项目需求,修改请求配置

综上

axios 安装完成。下一章 utils 工具构建,然后根据 utils 工具,完善 src/api/http.js 接口请求逻辑、src/store/user.js 登录逻辑、src/router/index.js 路由跳转逻辑。

下一章:Vue3+Vite+Pinia+Naive后台管理系统搭建之七:utils 工具构建

Vue 3 是一种用于构建用户界面的 JavaScript 框架,Vite 是一个由 Vue.js 官方团队开发的新一代构建工具,而 TypeScript (TS) 是一个静态类型检查的 JavaScript 超集。Pinia 是一个基于 Vue 3 的状态管理库。 在使用 Vite 创建 Vue 3 项目时,你可以选择使用 TypeScript,这样可以让你的代码更加稳健和可维护。首先,你需要安装 Vite: ``` npm init vite@latest my-vue-project --template vue-ts ``` 这将创建一个名为 `my-vue-project` 的新项目,并使用 Vue 3 和 TypeScript 模板。 接下来,你可以安装 Pinia 来管理你的应用状态: ``` npm install pinia ``` 然后,在你的应用程序中引入 Pinia: ```typescript import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' const app = createApp(App) const pinia = createPinia() app.use(pinia) app.mount('#app') ``` 现在你可以在你的组件中使用 Pinia 来管理状态了。例如,创建一个 counter store: ```typescript import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { state: () => ({ count: 0, }), actions: { increment() { this.count++ }, decrement() { this.count-- }, }, }) ``` 然后,在你的组件中使用这个 counter store: ```typescript <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> <button @click="decrement">Decrement</button> </div> </template> <script> import { useCounterStore } from './stores/counter' export default { name: 'Counter', setup() { const counterStore = useCounterStore() return { count: counterStore.count, increment: counterStore.increment, decrement: counterStore.decrement, } }, } </script> ``` 希望这可以帮助你开始使用 ViteVue 3、TypeScript 和 Pinia 创建应用程序!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yqcoder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值