实验目标
架构
采用vue+ts
前端
#App.vue
<template>
<div class="container">
<h1>Number Sorter</h1>
<input v-model="numbers" placeholder="Enter numbers separated by spaces" />
<button @click="sortNumbers">Sort Numbers</button>
<div v-if="sortedNumbers.length">
<h3>Sorted Numbers:</h3>
<p>{{ sortedNumbers.join(' ') }}</p>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import axios from 'axios'
const numbers = ref('')
const sortedNumbers = ref<number[]>([])
const sortNumbers = async () => {
try {
const response = await axios.post('http://localhost:3000/sort', {
numbers: numbers.value.split(' ').map(Number)
})
sortedNumbers.value = response.data.sortedNumbers
} catch (error) {
console.error('Error sorting numbers:', error)
}
}
</script>
<style scoped>
.container {
max-width: 600px;
margin: 0 auto;
text-align: center;
}
input {
margin-right: 10px;
padding: 5px;
}
button {
padding: 5px 10px;
}
h3 {
margin-top: 20px;
}
</style>
后端
#server.js
// server.js
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.post('/sort', (req, res) => {
let numbers = req.body.numbers;
if (!Array.isArray(numbers)) {
return res.status(400).json({ error: 'Invalid input' });
}
numbers = numbers.map(Number).sort((a, b) => a - b);
res.json({ sortedNumbers: numbers });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
运行
前端:npm run dev
后端:node server.js
效果图
在上面输入栏中输入待排列的数字,点击Sort Numbers
会在下方出现排列好的数字