Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

computed v-model in select tag in Vuejs2

Tags:

I have a component whose markup is

<select id="create-claim-start_date" type="text" class="form-control" v-model="startPeriod">
                                  <option value="0">January</option>
                                  <option value="3">April</option>
                                  <option value="6">July</option>
                                  <option value="8">October</option>
                                </select>

where startPeriod is a computed property

..........
data() {
   return { form: { claim_start_date: null } }
},
computed: {
      startPeriod: {
        get: function(){
          var d = window.moment();
          return d.get('month');
        },
        set: function(p) {
          var dt = window.moment()
          dt.set(p,'month');
          this.form.claim_start_date = dt.get('YYYY-mm-dd');
        }
      }
    }
   ........

Can I use a computed property as a model? Would the computed property trigger the update of a data property?

like image 582
KArneaud Avatar asked Nov 29 '16 21:11

KArneaud


2 Answers

If you need to update the value of claim_start_date when the select changes you can use a watcher.

Here is an example:

var app = new Vue({
  el: '#app',
  data: {
    startPeriod: '0',
    form: {
      claim_start_date: 'defaultValue'
    }
  },

  watch: {
    startPeriod: function(newValue, oldValue) {
      this.form.claim_start_date = "new value " + newValue;
    }
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.0/moment.min.js"></script>   

<div id="app">
  <select id="create-claim-start_date" type="text" class="form-control" v-model="startPeriod">
    <option value="0">January</option>
    <option value="3">April</option>
    <option value="6">July</option>
    <option value="8">October</option>
  </select>

  {{form.claim_start_date}}

</div>
like image 64
Mihai Vilcu Avatar answered Sep 22 '22 16:09

Mihai Vilcu


It seems like you may be taking that value and are going to use it later to create a Moment object...might it just be easier to use a Date/Moment object for the option values to begin with?

You can bind javascript values (i.e. objects) to the options values. You may need to adjust how you are setting the dates since we don't know the year/day.

<select id="create-claim-start_date" class="form-control" v-model="startPeriod">
    <option :value="moment('2016-01-01')">January</option>
    <option :value="moment('2016-04-01')">April</option>
    <option :value="moment('2016-07-01')">July</option>
    <option :value="moment('2016-10-01')">October</option>
</select>
like image 42
Mike Harrison Avatar answered Sep 22 '22 16:09

Mike Harrison