在Vue3中通过axios请求后端数据是非常常用的方法,这节课我们来简单学习下。
本节课需要依赖一个第三方库,我们先安装:
yarn add axios
我们先创建public/data.json,用于模拟后端返回的接口数据:
{
"msg": "成功",
"status": true,
"data": []
}
接着创建src/components/Demo36.vue,代码如下:
<script setup>
import {ref} from "vue";
import axios from "axios";
// 要渲染的数据
const data = ref(null)
// 发送请求
function loadData() {
axios.get("/data.json").then(function (resp) {
data.value = resp.data
}).catch(function (err) {
console.log("出错了。。。", err)
})
}
script>
<template>
<div>{{ data }}div>
<button @click="loadData">这是一个按钮button>
template>
<style lang="scss">
button {
color: red;
width: 100px;
height: 30px;
padding: 5px;
}
style>
接着,我们修改src/App.vue:
<script setup>
import Demo from "./components/Demo36.vue"
script>
<template>
<h1>欢迎跟着Python私教一起学习Vue3入门课程h1>
<hr>
<demo/>
template>
然后,我们浏览器访问:http://localhost:5173/
{
"name": "hello",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.6.2",
"countable": "^3.0.1",
"vue": "^3.3.8"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.5.0",
"sass": "^1.69.5",
"vite": "^5.0.0"
}
}
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
})
doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Vuetitle>
head>
<body>
<div id="app">div>
<script type="module" src="/src/main.js">script>
body>
html>
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
<script setup>
import Demo from "./components/Demo36.vue"
script>
<template>
<h1>欢迎跟着Python私教一起学习Vue3入门课程h1>
<hr>
<demo/>
template>
<script setup>
import {ref} from "vue";
import axios from "axios";
// 要渲染的数据
const data = ref(null)
// 发送请求
function loadData() {
axios.get("/data.json").then(function (resp) {
data.value = resp.data
}).catch(function (err) {
console.log("出错了。。。", err)
})
}
script>
<template>
<div>{{ data }}div>
<button @click="loadData">这是一个按钮button>
template>
<style lang="scss">
button {
color: red;
width: 100px;
height: 30px;
padding: 5px;
}
style>
yarn
yarn dev
浏览器访问:http://localhost:5173/