11、Vue 3 (2024 版)基础笔记 - 表单数据提交到服务器

作者: 温新

图书: 【Vue 3 setup 使用实记】

阅读: 71

时间: 2024-05-18 08:46:45

本篇文章演示 Vue3 双向数据绑定,并把如何提交到服务器(PHP)。

准备工作

1、创建组件

src/components/FormDemo.vue

<template></template>

<script setup lang="ts"></script>

2、引入组件

src/App.vue

<template>
    <FormDemo/>
</template>

<script setup lang="ts">
    import FormDemo from "@/components/FormDemo.vue";
</script>

3、安装 axios

$ pnpm i axios

4、配置后端服务代理

vite.config.ts

import { fileURLToPath, URL } from 'node:url'

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server: {
    // 配置代理
    proxy: {
      '/api': {
        target: 'http://b-laravel11-blog.test',
        changeOrigin: true,
        // 根据实际情况决定是否需要重写路径
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    },
    // 本地项目端口
    port: 5173
  }
})

双向数据绑定 & 提交数据到服务器

前置工作:后端准备好一个接收数据的方法。我已经准备好了,就不演示了。

1、提交数据到服务器

<template>
    <h3>提交数据到服务器</h3>

    <form @submit.prevent="submitForm">
        <p>姓名:<input type="text" v-model="formData.name"></p>
        <p>邮箱:<input type="email" v-model="formData.email"></p>
        <p>性别:
            <label v-for="gender in genders" :key="gender.id">
                <input type="radio" :value="gender.id" v-model="formData.genderId">
                {{ gender.name }}
            </label>
        </p>
        <p>爱好:
            <div v-for="hobby in hobbies" :key="hobby.id">
                <label>
                    <input type="checkbox" :value="hobby.id" v-model="formData.hobbies">
                    {{ hobby.name }}
                </label>
            </div>
        </p>
        <p>选择城市:
            <select v-model="formData.city">
                <option v-for="city in cities" :key="city.id" :value="city.id">{{ city.name }}</option>
            </select>
        </p>
        <button>提交</button>
    </form>

</template>

<script setup lang="ts">
    import {reactive} from 'vue'
    import axios from 'axios'

    const formData = reactive({
        name: '',
        email: '',
        genderId: 1,
        hobbies: [],
        city: 1
    });

    const genders = [
        { id: 1, name: '男' },
        { id: 2, name: '女' },
    ];

    const hobbies = [
        { id: 1, name: '篮球' },
        { id: 2, name: '足球' },
        { id: 3, name: '游泳' },
    ];

    const cities = [
        { id: 1, name: '北京' },
        { id: 2, name: '上海' },
        { id: 3, name: '广州' },
    ];

const submitForm = async () => {
    // 提交数据到服务器
    const response = await axios.post('http://b-laravel11-blog.test/api/test/save', formData);
    console.log(response.data)
}
</script>

2、我的后端方法

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class TestController extends Controller
{
    public function save(Request $request)
    {
        Log::info($request->all());
        
        return response()->json([
            'data'    => $request->all(),
            'message' => 'success',
        ]);
    }
}

3、测试

服务端日志输入:

[2024-04-09 23:29:53] local.INFO: array (
  'name' => '王美丽',
  'email' => 'wangmeili@ziruchu.com',
  'genderId' => 1,
  'hobbies' => 
  array (
    0 => 1,
    1 => 2,
    2 => 3,
  ),
  'city' => 3,
)  

浏览器端响应成功后的数据

{
    "data": {
        "name": "王美丽",
        "email": "wangmeili@ziruchu.com",
        "genderId": 1,
        "hobbies": [
            1,
            2,
            3
        ],
        "city": 3
    },
    "message": "success"
}
请登录后再评论