Vue3使用Cascader 级联选择器如何获取值并提交信息

我写了一个用户对象,有address地址字段,我怎么将用户选择的级联数据selectedValue值传给address,并将对象返回给后端,核心代码实现了该问题。

<script>

核心代码:

javascript 复制代码
//获取住址并更新给address
    let selectedValue = ref([]);
    // 监听 selectedValue 的变化
    watch(selectedValue, (newValue) => {
      formData.address = newValue.join(",");
    });
    const handleChange = (value) => {
      console.log(`value==${value}`);
      // 更新 selectedValue 的值
      selectedValue.value = value;
    };

js完整代码

javascript 复制代码
<script >
import { reactive, ref, watch } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";

export default {
  setup() {
    const router = useRouter();

    //注册用户表单信息
    const formData = reactive({
      username: "",
      password: "",
      tel: "",
      gender: "",
      age: null,
      birthday: "",
      address: "",
    });

    //获取住址并更新给address
    let selectedValue = ref([]);
    // 监听 selectedValue 的变化
    watch(selectedValue, (newValue) => {
      formData.address = newValue.join(",");
    });
    const handleChange = (value) => {
      console.log(`value==${value}`);
      // 更新 selectedValue 的值
      selectedValue.value = value;
    };

    //住址(固定信息)
    const options = [
      {
        value: "河南省",
        label: "河南省",
        children: [
          {
            value: "开封市",
            label: "开封市",
            children: [
              {
                value: "兰考县",
                label: "兰考县",
              },
              {
                value: "尉氏县",
                label: "尉氏县",
              },
              {
                value: "龙亭区",
                label: "龙亭区",
              },
              {
                value: "禹王台区",
                label: "禹王台区",
              },
            ],
          },
          {
            value: "郑州市",
            label: "郑州市",
            children: [
              {
                value: "中原区",
                label: "中原区",
              },
              {
                value: "二七区",
                label: "二七区",
              },
              {
                value: "管城回族区",
                label: "管城回族区",
              },
              {
                value: "金水区",
                label: "金水区",
              },
            ],
          },
        ],
      },
      {
        value: "广东省",
        label: "广东省",
        children: [
          {
            value: "深圳市",
            label: "深圳市",
            children: [
              {
                value: "福田区",
                label: "福田区",
              },
              {
                value: "龙岗区",
                label: "龙岗区",
              },
              {
                value: "南山区",
                label: "南山区",
              },
              {
                value: "宝安区",
                label: "宝安区",
              },
            ],
          },
          {
            value: "广州市",
            label: "广州市",
            children: [
              {
                value: "海珠区",
                label: "海珠区",
              },
              {
                value: "天河区",
                label: "天河区",
              },
              {
                value: "荔湾区",
                label: "荔湾区",
              },
              {
                value: "越秀区",
                label: "越秀区",
              },
            ],
          },
        ],
      },
    ];
    const submitForm = async () => {
      try {
        const response = await axios.post("/api/saveUser", formData, {
          headers: {
            "Content-Type": "application/json", // 根据后端需要的类型设置
          },
        });

        if (response.data.code > 0) {
          router.push({ name: "Login" }); // 成功时跳转到登录页
        } else if (response.data.code === -2) {
          alert(response.data.desc); // 处理特定错误码,弹出警告
        } else {
          alert("注册失败,请重试!"); // 其他错误情况
        }
      } catch (error) {
        alert("注册失败,请重试!"); // 捕获异常情况
      }
    };

    return {
      formData,
      submitForm,
      options,
      handleChange,
      selectedValue,
    };
  },
};
</script>

<template>

html 复制代码
 <!-- 级联选择器 -->
        <el-cascader
          v-model="selectedValue"
          :options="options"
          @change="handleChange"
        />

注册页面完整代码

javascript 复制代码
<template>
  <div class="register-form">
    <h2>用户注册</h2>
    <form @submit.prevent="submitForm">
      <div class="form-group">
        <label for="username">用户名</label>
        <input type="text" id="username" v-model="formData.username" required />
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input
          type="password"
          id="password"
          v-model="formData.password"
          required
        />
      </div>
      <div class="form-group">
        <label for="tel">手机号</label>
        <input type="text" id="tel" v-model="formData.tel" required />
      </div>
      <div class="form-group">
        <label>性别</label>
        <label>
          <input type="radio" v-model="formData.gender" value="男" />
          男
        </label>
        <label>
          <input type="radio" v-model="formData.gender" value="女" />
          女
        </label>
      </div>
      <div class="form-group">
        <label for="age">年龄</label>
        <input type="number" id="age" v-model.number="formData.age" required />
      </div>
      <div class="form-group">
        <label for="birthday">出生日期</label>
        <input type="date" id="birthday" v-model="formData.birthday" required />
      </div>
      <div class="form-group">
        <label for="address">住址</label>
        <!-- 级联选择器 -->
        <el-cascader
          v-model="selectedValue"
          :options="options"
          @change="handleChange"
        />
        <!-- <textarea
          id="address"
          v-model="formData.address"
          rows="3"
          required
        ></textarea> -->
      </div>
      <button type="submit">注册</button>
    </form>
  </div>
</template>
<script >
import { reactive, ref, watch } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";

export default {
  setup() {
    const router = useRouter();

    //注册用户表单信息
    const formData = reactive({
      username: "",
      password: "",
      tel: "",
      gender: "",
      age: null,
      birthday: "",
      address: "",
    });

    //获取住址并更新给address
    let selectedValue = ref([]);
    // 监听 selectedValue 的变化
    watch(selectedValue, (newValue) => {
      formData.address = newValue.join(",");
    });
    const handleChange = (value) => {
      console.log(`value==${value}`);
      // 更新 selectedValue 的值
      selectedValue.value = value;
    };

    //住址(固定信息)
    const options = [
      {
        value: "河南省",
        label: "河南省",
        children: [
          {
            value: "开封市",
            label: "开封市",
            children: [
              {
                value: "兰考县",
                label: "兰考县",
              },
              {
                value: "尉氏县",
                label: "尉氏县",
              },
              {
                value: "龙亭区",
                label: "龙亭区",
              },
              {
                value: "禹王台区",
                label: "禹王台区",
              },
            ],
          },
          {
            value: "郑州市",
            label: "郑州市",
            children: [
              {
                value: "中原区",
                label: "中原区",
              },
              {
                value: "二七区",
                label: "二七区",
              },
              {
                value: "管城回族区",
                label: "管城回族区",
              },
              {
                value: "金水区",
                label: "金水区",
              },
            ],
          },
        ],
      },
      {
        value: "广东省",
        label: "广东省",
        children: [
          {
            value: "深圳市",
            label: "深圳市",
            children: [
              {
                value: "福田区",
                label: "福田区",
              },
              {
                value: "龙岗区",
                label: "龙岗区",
              },
              {
                value: "南山区",
                label: "南山区",
              },
              {
                value: "宝安区",
                label: "宝安区",
              },
            ],
          },
          {
            value: "广州市",
            label: "广州市",
            children: [
              {
                value: "海珠区",
                label: "海珠区",
              },
              {
                value: "天河区",
                label: "天河区",
              },
              {
                value: "荔湾区",
                label: "荔湾区",
              },
              {
                value: "越秀区",
                label: "越秀区",
              },
            ],
          },
        ],
      },
    ];
    const submitForm = async () => {
      try {
        const response = await axios.post("/api/saveUser", formData, {
          headers: {
            "Content-Type": "application/json", // 根据后端需要的类型设置
          },
        });

        if (response.data.code > 0) {
          router.push({ name: "Login" }); // 成功时跳转到登录页
        } else if (response.data.code === -2) {
          alert(response.data.desc); // 处理特定错误码,弹出警告
        } else {
          alert("注册失败,请重试!"); // 其他错误情况
        }
      } catch (error) {
        alert("注册失败,请重试!"); // 捕获异常情况
      }
    };

    return {
      formData,
      submitForm,
      options,
      handleChange,
      selectedValue,
    };
  },
};
</script>

<style scoped>
.register-form {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input[type="text"],
input[type="password"],
input[type="number"],
input[type="date"],
textarea {
  width: 100%;
  padding: 8px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  display: block;
  width: 100%;
  padding: 10px;
  font-size: 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}
</style>
  
相关推荐
苦瓜小生15 分钟前
【前端】|【js手撕】经典高频面试题:手写实现function.call、apply、bind
java·前端·javascript
踩着两条虫34 分钟前
AI驱动的Vue3应用开发平台深入探究(十):物料系统之内置组件库
android·前端·vue.js·人工智能·低代码·系统架构·rxjava
和沐阳学逆向38 分钟前
我现在怎么用 CC Switch 管中转站,顺手拿 Codex 举个例子
开发语言·javascript·ecmascript
慧一居士1 小时前
nuxt3 项目和nuxt4 项目区别和对比
前端·vue.js
kgduu3 小时前
js之客户端存储
javascript·数据库·oracle
四千岁3 小时前
2026 最新版:WSL + Ubuntu 全栈开发环境,一篇搞定!
javascript·node.js
竹林8183 小时前
从“连接失败”到丝滑登录:我用 ethers.js 连接 MetaMask 的完整踩坑实录
前端·javascript
神舟之光3 小时前
jwt权限控制简单总结(乡村意见簿-vue-express-mongdb)
前端·vue.js·express
铭毅天下3 小时前
EasySearch Rules 规则语法速查手册
开发语言·前端·javascript·ecmascript
bjzhang754 小时前
使用 HTML + JavaScript 实现 SQL 智能补全功能
javascript·html·sql智能补全