1.环境以及创建项目
1.下载nvm,参考下面链接(转载)
mac环境下载nvm
2.下载npm
3.使用idea或者vscode启动
4.创建代码:vue create “项目名称”。
5.选择自动下载默认vue3就可以
2.components新建自定义组件
1.
2.创建Test.vue组件,并且使用axios与后端关联
比如Test.vue代码。一个输入用户姓名,学号,年龄的样式。并且绑定了submitForm按钮。在submitForm函数下面常见了一个对象,对象里面有刚才输入的姓名,学号,年龄的数值,并且把他发给后端。
<template>
<div class="form-container">
<div class="form-group">
<label for="name">姓名:</label>
<input type="text" id="name" v-model="name" placeholder="请输入姓名">
</div>
<div class="form-group">
<label for="studentId">学号:</label>
<input type="text" id="studentId" v-model="studentId" placeholder="请输入学号">
</div>
<div class="form-group">
<label for="age">年龄:</label>
<input type="number" id="age" v-model="age" placeholder="请输入年龄">
</div>
<button @click="submitForm">提交</button>
</div>
</template>
<script>
import axios from 'axios';
import { ref } from 'vue';
import router from "@/router/index.js";
export default {
setup() {
//vue3语法
const name = ref("");
const studentId = ref("");
const age = ref();
const submitForm = ()=>{
const formData = {
name: name.value,
id: studentId.value,
age: age.value
};
console.log("1: ",formData);
axios.post('http://localhost:8989/submit-form',formData)
.then(response => {
console.log(response.data);
router.push("/child");
})
.catch(error => {
console.error(error);
});
}
return{
submitForm,name,age,studentId
}
}
}
</script>
<style>
.form-container {
max-width: 400px;
margin: 0 auto;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.form-group {
margin-bottom: 10px;
}
button {
background-color: #007bff;
color: #fff;
padding: 5px 10px;
border: none;
cursor: pointer;
}
</style>
3.配置路由(router)
如果创建的项目没有路由,新建包然后加入,相关代码,自行按照自己代码调整
import { createRouter, createWebHashHistory } from 'vue-router'
// import HomeView from '../views/HomeView.vue'
import Test from '@/components/Test.vue'
const routes = [
// {
// path: '/',
// name: 'home',
// component: HomeView
// },
// {
// path: '/about',
// name: 'about',
// // route level code-splitting
// // this generates a separate chunk (about.[hash].js) for this route
// // which is lazy-loaded when the route is visited.
// component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
// },
{
path: '/test',
name: 'test',
component: ()=>import('../components/Test.vue')
},
{
path: '/child',
name: 'child',
component: ()=>import('../components/Child.vue')
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router