Search code examples
javascriptvue.jsv-model

Vue.js v-model to local state


I am passing in data to my component though props. I use beforeMount to store the data in the local state via the data function. I then need to update that local state onchange.

I am attempting to use v-model to data bind to the local state but when I change the input value it doesn't change the data function.

I think I am missing something simple... Help is appreciated, thanks! :)

HTML

<div id="labDataWrap" v-if="showLabData">
        <h2>Cannabinoid Profile</h2>
        <ul>
            <li v-for="( value, key ) in cannabanoidProfile" :class="[ key.toLowerCase() ]">
                <md-field class="md-focused">
                    <label> {{ key }} </label>
                    <md-input v-model="cannabanoidObj[key]" type="number" :name="key" :value="value">{{ value }}</md-input>
                </md-field>
            </li>   
        </ul>
        <h2>Terpene Profile</h2>
        <ul>
            <li v-for="( value, key ) in terpeneProfile" :class="[ key.toLowerCase() ]">
                <md-field class="md-focused">
                    <label> {{ key }} </label>
                    <md-input v-model="terpeneObj[key]" type="number" :name="key" :value="value">{{ value }}</md-input>
                </md-field>
            </li>
        </ul>
        <div class="buttonWrap">
            <md-button id="saveLabData" @click="saveLabData">Save</md-button>
            <md-button id="closeLabData" @click="toggleLabData">Close</md-button>
        </div>
    </div>

JS

name: "Row",
props: ["other props omitted for post","cannabanoidProfile", "terpeneProfile"],
beforeMount(){
    this.cannabanoidObj = this.cannabanoidProfile;
    this.terpeneObj = this.terpeneProfile;
},
data: function(){
    return {
        cannabanoidObj: {},
            terpeneObj: {},
            isDisabled: true,
            showLabData: false
        }
    },

Solution

  • From documentation:

    Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion.

    To change property in your cannabanoidObj use vm.$set