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>
  
相关推荐
之歆6 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
Maimai108086 小时前
React如何用 @microsoft/fetch-event-source 落地 SSE:比原生 EventSource 更灵活的实时推送方案
前端·javascript·react.js·microsoft·前端框架·reactjs·webassembly
candyTong6 小时前
Claude Code 的 Edit 工具是怎么工作的
javascript·后端·架构
卡卡军9 小时前
agmd 1.0 重磅升级——Rust 重写,性能起飞
javascript·rust
Larcher9 小时前
🔥 告别抓瞎:用 Claude Code (cc) 优雅接手与维护已有项目
javascript·机器学习·前端框架
JYeontu9 小时前
轮播图不够惊艳?试下这个立体卡片轮播图
前端·javascript·css
亲亲小宝宝鸭9 小时前
如何监听DOM尺寸的变化?element-resize-detector 和 resizeObserver
前端·javascript
代码煮茶9 小时前
Vite 5.0 新特性深度解析:更快、更干净、更未来的前端构建利器
vue.js
卷帘依旧12 小时前
Generator 全面解析 + async/await 深度对比
前端·javascript
weixin_4713830312 小时前
统一缩放单位基础(px、em、rem)
开发语言·javascript·ecmascript