在vuejs中的组件之间传递数据

时间:2018-05-16 22:40:35

标签: javascript vue.js axios

我有我的费用跟踪器应用。我在添加费用方面遇到了问题。 我有两个组件负责:addCategory.vue和selectCategory.vue。

这是我的selectCategory.vue组件:

| userName    | startDate  | endDate    | weekDay |  
| :---------: | :--------: | :--------: | :-----: |  
| Test User 1 | 2011-03-30 | 2011-04-05 | 1       |  
| Test User 2 | 2016-10-05 | 2016-10-07 | 5       |  
| Test User 3 | 2018-05-22 | 2018-05-26 | 4       |  

这是我的addExpense.vue组件:

| userName    | startDate  | weekDay    |
| :---------: | :--------: | :--------: |
| Test User 1 | 2011-03-30 | 1          |
| Test User 1 | 2011-03-31 | 1          |
| Test User 1 | 2011-04-01 | 1          |
| Test User 1 | 2011-04-02 | 1          |
| Test User 1 | 2011-04-03 | 1          |
| Test User 1 | 2011-04-04 | 1          |
| Test User 1 | 2011-04-05 | 1          |
| Test User 2 | 2016-10-05 | 5          |
| Test User 2 | 2016-10-06 | 5          |
| Test User 2 | 2016-10-07 | 5          |
| Test User 3 | 2018-05-22 | 4          |
| Test User 3 | 2018-05-23 | 4          |
| Test User 3 | 2018-05-24 | 4          |
| Test User 3 | 2018-05-25 | 4          |
| Test User 3 | 2018-05-26 | 4          |

我需要帮助,因为当我尝试添加费用时,字段为' categoryId'仍然是空的。 我使用Events来传递类别的名称,但我不知道如何将category.id添加到Expense。

1 个答案:

答案 0 :(得分:0)

您的代码中的问题:

  1. 您需要添加一个数据属性以保存用户选择的选项,因此添加一个数据属性= selectedCategory

  2. 您没有绑定select的选项的值,并且您没有绑定select的值,因此为v-model="selectedCategory"添加<select>并添加{{1 } :value="category"

  3. 您似乎绑定了<option>的错误事件(事件= 已选择更可能是您自定义的事件名称),更改为<select>

  4. 最后,在@change="selectChange(selectedCategory)"中,收听event = addExpense.vue

    如下面演示:

    select-cat
    Vue.config.productionTip = false
    Vue.component('select-category', {
    
      template: `<div>
                    <select class="custom-select" v-model="selectedCategory" @change="selectChange(selectedCategory)">
                        <option v-for="category in categories" :value="category">{{ category.title }}</option>
                    </select>
                </div>`,
        data() {
            return {
                categories: [],
                errors: [],
                selectedCategory: null
            }
        },
        mounted() {
            this.categories = [
              {'id':1, 'title': 'abc'},
              {'id':2, 'title': 'xyz'}
            ]
        },
        methods: {
          selectChange: function(newCatetory) {
            this.$emit('select-cat',newCatetory)
          }
        }
    })
    
    new Vue({
      el: '#app',
      data() {
        return {
          categorySelected: null
        }
      },
      watch: {
        categorySelected: function (newVal, oldVal) {
          console.log('changed to ' + newVal.id + ' from ' + (oldVal ? oldVal.id : oldVal))
        }
      },
      methods:{
        chooseCategory: function(data) {
          this.categorySelected = data
        }
      }
    })

相关问题