loreeemartiii
loreeemartiii

Reputation: 395

VueJS can't update v-text-field value dynamically

I dynamically draw form input component (as in the image) using this code: In this case the key can be "name","gruppo","codice" and so on.

<v-row>
    <v-col v-for="(key,i) in keys_visible" :key="key" v-if="headers_visible[i].visible == true" cols="12" sm="12" md="12"
        v-if="!(headers_visible[i].type == 'bit' && editedItem[key] == -9)">
        <v-text-field @change="comp_change(key)" v-else-if="headers_visible[i].type == 'varchar'" v-model="editedItem[key]" :label="headers_visible[i].text"></v-text-field>
    </v-col>
</v-row>

Then I have comp_change function which is defined in methods block:

comp_change (par1) {    
    var self = this;    
    self.editedItem["name"] = "example text";           
},

I have placed a debugger; at the beginning of comp_change function, and it stops everytime so the function is triggered, but without displaying new value in "Nome" field (which v-model is editedItem["name"]). Why after comp_change I can't see "example text" in the field?

The form is already opened when I fire change

enter image description here

Upvotes: 2

Views: 6209

Answers (1)

Chris
Chris

Reputation: 4810

This is likely a reactivity issue. You should read up on this here. Also, if you use v-model, you do not need to set the value yourself, meaning you can do away with the @change call. You have two options as I see it.

a. Use root data objects on your component instead of an array/object and then use v-model as normal. This looks like:

<template>
    <v-text-field v-model="name" />
    <v-text-field v-model="email" />
</template>
<script>
export default {
    data() {
        return {
            name: '',
            email: '',
            etc: ''
        }
    }
}
</script>

Now, when your form fields are updated by the user, you won't need to use @change to set the value. It will happen automatically.

b. Or, set the model with Vue.set(). In this case, you are not going to use v-model. Instead, you have defined your own methods to manage the data. This looks like:

<template>
    <v-text-field @change="comp_change(key)" />
</template>
<script>
import Vue from 'vue';

export default {
    data() {
        return {
            editedItem: {}
        }
    },
    methods: {
        comp_change (par1) {    
            Vue.set( this.editedItem, 'name', 'example text' );     
        }
    }
}
</script>

Upvotes: 2

Related Questions