[Vuejs]-Passing data between components in vuejs

0👍

The issues in your codes:

  1. you need to add one data property to save which option the user selected, so add one data property=selectedCategory

  2. you didn’t bind the value for the options of the select, and you didn’t bind the value of the select, so add v-model="selectedCategory" for <select> and add :value="category" for <option>

  3. It seems you bind wrong event (event=selected more likely is the event name you customized) for <select>, change to @change="selectChange(selectedCategory)"

Finally, in addExpense.vue, listen event=select-cat.

Like below demo:

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
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
   <div class="form-group">
      <label for="expense-category">Kategoria</label>
      <select-category @select-cat="chooseCategory($event)"></select-category>
  </div>
</div>

Leave a comment