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>
  
相关推荐
小马哥编程1 小时前
Function.prototype和Object.prototype 的区别
javascript
苹果醋31 小时前
React系列(八)——React进阶知识点拓展
运维·vue.js·spring boot·nginx·课程设计
王小王和他的小伙伴2 小时前
解决 vue3 中 echarts图表在el-dialog中显示问题
javascript·vue.js·echarts
学前端的小朱2 小时前
处理字体图标、js、html及其他资源
开发语言·javascript·webpack·html·打包工具
outstanding木槿2 小时前
react+antd的Table组件编辑单元格
前端·javascript·react.js·前端框架
好名字08212 小时前
前端取Content-Disposition中的filename字段与解码(vue)
前端·javascript·vue.js·前端框架
摇光933 小时前
js高阶-async与事件循环
开发语言·javascript·事件循环·宏任务·微任务
隐形喷火龙3 小时前
element ui--下拉根据拼音首字母过滤
前端·vue.js·ui
胡西风_foxww3 小时前
【ES6复习笔记】Class类(15)
javascript·笔记·es6·继承··class·静态成员
布兰妮甜3 小时前
使用 WebRTC 进行实时通信
javascript·webrtc·实时通信