Vue.js组件传值问题:费用追踪应用添加费用时categoryId为空
解决费用追踪应用中categoryId为空的问题
我来帮你搞定这个问题!你的categoryId字段始终为空,主要是因为两个组件的事件传递和表单绑定细节没处理对,咱们一步步修正:
第一步:修复selectCategory.vue的选择逻辑
你的选择组件里有两个关键问题:select的事件绑定错误,而且option没有关联分类ID。修改如下:
<template> <div> <!-- 把@selected改成@change,添加处理方法 --> <select class="custom-select" @change="handleCategorySelect"> <!-- 给option绑定value为category.id,同时设置唯一key --> <option v-for="category in categories" :key="category.id" :value="category.id"> {{ category.title }} </option> </select> </div> </template> <script> import axios from 'axios'; export default { data() { return { categories: [], errors: [] } }, created() { axios.get(`http://localhost:3000/categories`) .then(response => { this.categories = response.data; console.log(response.data); }) .catch(e => { this.errors.push(e) }) }, methods: { handleCategorySelect(event) { // 根据选中的ID匹配对应的分类对象 const selectedId = event.target.value; const selectedCategory = this.categories.find(cat => cat.id === selectedId); // 向父组件传递选中的分类对象 this.$emit('select-cat', selectedCategory); } } } </script>
核心修改点:
- 把
@selected替换为@change(select元素的正确触发事件是change) - 给option绑定
:value="category.id",确保选中时能获取到分类ID - 添加
handleCategorySelect方法,找到选中的分类对象并通过事件传递给父组件
第二步:修复addExpense.vue的事件接收逻辑
父组件里的问题在于chooseCategory方法没有接收子组件传递的参数,而且多余的v-model绑定无效(子组件未实现v-model逻辑)。修改如下:
<template> <div class="card"> <div class="card-header"> <h4>Dodaj nowy wydatek</h4> </div> <form v-on:submit.prevent="addExpense"> <div class="card-body"> <!-- 其他表单字段保持不变 --> <div class="form-group"> <label for="expense-category">Kategoria</label> <!-- 去掉无效的v-model,只保留事件监听 --> <select-category @select-cat="chooseCategory"></select-category> </div> <br> <div class="form-group"> <button class="btn btn-primary" @click="showAlert">Dodaj nowy wydatek</button> </div> </div> </form> </div> </template> <script> import axios from 'axios'; import selectCategory from './selectCategory.vue'; export default { components: { 'select-category': selectCategory }, data(){ return { Expense: { title:'', amount: '', date:'', categoryId:'' } // 删掉多余的Category变量,不需要额外维护这个状态 } }, methods : { // 接收子组件传递的分类对象 chooseCategory(selectedCategory){ // 直接将选中分类的ID赋值给Expense.categoryId this.Expense.categoryId = selectedCategory.id; }, showAlert(){ this.$alert.success({ message: 'Wydatek dodany poprawnie' }) }, addExpense(){ let newExpense = { title : this.Expense.title, amount : this.Expense.amount, date : this.Expense.date, categoryId: this.Expense.categoryId } console.log(newExpense); axios.post(`http://localhost:3000/expenses`, newExpense) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }) } } } </script>
核心修改点:
- 移除
select-category上无效的v-model="Category.id" - 让
chooseCategory方法接收子组件传递的selectedCategory参数 - 直接用
selectedCategory.id给Expense.categoryId赋值
这样修改之后,当你选择分类时,对应的ID就会正确赋值给Expense.categoryId,添加费用的时候这个字段就不会为空了!
内容的提问来源于stack exchange,提问作者amazintesla
相关产品推荐
相关产品推荐

