vue3+vite+json-sever+前后数据分离案例-----axios

一.通过vite搭建项目

安装指令:npm init vite@latest  项目名字  -- --template vue

二.json-server依赖包安装与启动配置

1.安装json-server依赖

npm install json-server
或者
cnpm install json-server-----淘宝镜像安装

2.json-server启动项配置

(1)在src的同级目录先创建文件夹mock

 (2)并创建mock/db.json文件,添加数据-----想要什么数据可自行添加

{
    "infomation": [
        {
            "id": 1,
            "title": "json-server 的第1条数据",
            "desc": "奥特曼不想打小怪兽,明明可以做好朋友的",
            "author": "被奥特曼打了很久的怪兽"
        },
        {
            "id": 2,
            "title": "json-server 的第2条数据",
            "desc": "葫芦娃不想去救爷爷,一个一个的去送不好",
            "author": "种出七个葫芦的爷爷"
        },
        {
            "id": 1,
            "title": "json-server 的第一条数据",
            "desc": "王者荣耀其实不是很好玩,这并不是我内心的真话",
            "author": "想玩游戏的我"
        }
    ],
    "infomation2": [
        {
            "id": 11,
            "title": "json-server 的第11条数据",
            "desc": "奥特曼不想打小怪兽,明明可以做好朋友的",
            "author": "被奥特曼打了很久的怪兽"
        },
        {
            "id": 12,
            "title": "json-server 的第12条数据",
            "desc": "葫芦娃不想去救爷爷,一个一个的去送不好",
            "author": "种出七个葫芦的爷爷"
        },
        {
            "id": 12,
            "title": "json-server 的第13条数据",
            "desc": "王者荣耀其实不是很好玩,这并不是我内心的真话",
            "author": "想玩游戏的我"
        }
    ]
}

 (3)page.json配置启动项目—– "mock": "json-server --watch mock/db.json --port 3000"

mock —–启动命令

json-server —–实际启动命令

--watch —– 侦听状态

mock/db.json —— 启动的文件

--port 3000" —— 启动的端口号

 3.启动服务器与项目----npm run mock

mock---是你建立的文件名

(1)启动json-server服务器

 (2)启动项目

npm run serve-----vue脚手架命令符

npm run dev ----vite命令符

我们这里用的是vue3+vite-----所以用第二种

 *三.axios请求数据

1.安装axios依赖

npm install axios
或者
cnpm install axios

查看是否安装成功可在项目中的page.json配置查看是否有axios

 2.封装axios

在实际的项目中,我们一般不会直接将安装好的axios进行使用,而是进行二次封装,接下来我们来简单的封装

(1)创建 axios/http.js

在src文件在下创建axios文件夹,在axios里创建 http.js文件

 (2)在http.js进行编写

     1.导入axios配置文件

//axios配置文件
import axios from "axios";

    2.添加四个方法---查询,添加,修改,删除

//查询数据 url---地址  data---传递的数据 一般通过id传送
const get = (url) => {
  return axios.get(url);
};
//添加数据
const post = (url, data) => {
  return axios.post(url, data);
};
//修改数据
const put = (url, data) => {
  return axios.post(url, data);
};
//删除数据
const del = (url) => {
  return axios.post(url, data);
};

3.将二次封装好的axios导出 

export { get, post, put, del };

3.在项目中使用axios请求方法

附:请求跨域方法可参考官网:选项式---vue/cli  组合式----vue3简介 | Vue.jsVue.js - 渐进式的 JavaScript 框架icon-default.png?t=N7T8https://cn.vuejs.org/guide/introduction.html

  1.vue/cli脚手架配置代理——vue.config.js

项目的端口为8080,然后json文件的端口为3000,这样就会涉及到跨域,解决跨域的方式很多种,此处讲解一下配置proxy代理 在根目录下创建文件vue.config.js--------vue/cli脚手架模式

module.exports = {
  devServer: {
    proxy: {
      "/api": {
        // 此处的写法,目的是为了 将/api 替换成 http://localhost:3000
        target: "http://localhost:3000",
        //是否跨域
        changeOrigin: true,
        //路径重写 下面示例为 将 /api 替换成空
        pathRewrite: {
          "^/api": "",
        },
      },
    },
  },
};

target :地址为json-server运行出来的后台数据地址(同下)

2.vite配置代理——-vite.config.js

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  //跨域
  server: {
    proxy: {
      "/api": {
        //服务器请求域名
        target: "http://localhost:3000",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
});

3.发送axios请求

(1)获取数据---get

<!-- 视图层 -->
<template>
    <div class="about">
    <h1>数据测试</h1>
    <button @click="sendRequest">查询infomation的所有信息</button>
  </div>
  <ul>
    <li v-for="items in infoList">{{items.title}}</li>
  </ul>
</template>

<!-- 逻辑层 -->
<script setup>
//当前页面用到哪些就引入哪些方法
import { get, post, put, del } from "./axios/http.js";
import { ref } from "vue";

const infoList = ref([]);
//查询数据
//async与await将数据进行转换
async function sendRequest() {
  let res = await get("/api/infomation");
  infoList.value = res.data;
}
</script>

<!-- 样式层 -->
<style  scoped>
</style>

axios获取数据的时候会得到Promise数据,所以我们要对它进行数据转换,常用的方法async与await

结果:点击查询数据

                     

(2)添加数据---post

<!-- 视图层 -->
<template>
    <div class="about">
    <h1>数据测试</h1>
    <button @click="sendRequest">查询infomation的所有信息</button>
  
    <button @click="sendRequest3">添加infomation数据</button>
    
  </div>
  <ul>
    <li v-for="items in infoList">{{items.title}}</li>
  </ul>
</template>

<!-- 逻辑层 -->
<script setup>
//当前页面用到哪些就引入哪些方法
import { get, post, put, del } from "./axios/http.js";
import { ref } from "vue";

const infoList = ref([]);

async function sendRequest3() {
  let res3 = await post("/api/infomation", {
    title: "json-server 的第xxx条数据",
    desc: "奥特曼不想打小怪",
    author: "被奥特曼打了",
  });
  console.log(res3, "post添加infomation数据成功");
}
</script>

<!-- 样式层 -->
<style  scoped>
</style>

结果:点击添加按钮

 (3)修改数据-----put

<!-- 视图层 -->
<template>
    <div class="about">
    <h1>数据测试</h1>
    <button @click="sendRequest4">修改infomation的id为1信息</button>
  </div>
</template>

<!-- 逻辑层 -->
<script setup>
//当前页面用到哪些就引入哪些方法
import { get, post, del, put } from "./axios/http.js";
import { ref } from "vue";


// put修改infomation的id为1信息
async function sendRequest4() {
  let res4 = await put("/api/infomation/1", {
    title: "json-server 的第x+2条数据",
    desc: "奥特曼想打小怪111333333",
    author: "2222被奥特曼打了",
  }).then((res) => {
    console.log(res);
  });
  // console.log(res4, "pust修改infomation的id为1信息成功");
}
</script>

<!-- 样式层 -->
<style  scoped>
</style>

结果:修改成功

 (4)删除数据----del

<!-- 视图层 -->
<template>
    <div class="about">
    <h1>数据测试</h1>
    <button @click="sendRequest5">删除infomation的id为1信息</button>
  </div>
</template>

<!-- 逻辑层 -->
<script setup>
//当前页面用到哪些就引入哪些方法
import { get, post, del, put } from "./axios/http.js";
import { ref } from "vue";

// del删除infomation的id为1信息
async function sendRequest5() {
  let res4 = await del("/api/infomation/1");
  console.log(res4, "del删除infomation的id为1信息数据成功");
}
</script>

<!-- 样式层 -->
<style  scoped>
</style>

结果:删除成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值