Do not set the value of an input with VueJs

0

I have an input text with typeahead that I use to search for a user

This I do through a component of vue, the template is:

<template>
    <div>
        <label for="">Buscar Usuario</label>
        <input type="text" class="form-control search-user" required="" placeholder="Usuario" autocomplete="off"/>
        <input type="hidden" name="id_user" required="" v-model="user"/>
    </div>
</template>


<script>
export default {
    data() {
        return {
            user: ''
        }
    },
    mounted() {
        $('.search-user').typeahead({
            source: function (query, result) {
                return $.post("/FinDraT/users/getUsersTypeAhead", {query: query}, function (data) {
                    return result(data);
                });
            },
            updater: function (item) {
               this.user = item.id;

                return item;
            }
        });
    }
}

The problem is that when selecting the user, in the updater method I want to set the id in the hidden input that I then use it to save the user in the model I am in.

The input hidden probe with v-model: "user",: value="user" and none of them set the value

    
asked by Juan Pablo B 07.11.2017 в 21:47
source

2 answers

2

The problem is the scope of javascript in which you work.

When using function the code that will be executed in that function will have its own scope , which is different from the environment, to give you an example, this is what was done before:

function () {
    // main scope
    var self = this;
    function () {
        // second scope
        self === this; // false
        // como te das cuenta, aquí this es otro objeto
    }
}

For this reason it does not work for you, for that the arrow functions was created, which allow us to keep the scope in the following way:

function () {
    var self = this;
    () => {
        self === this; // true
    }
}
  

THESE EXAMPLES ARE DEMONSTRATIVE

For your case, it would apply as follows:

mounted() {
    $('.search-user').typeahead({
        source: function (query, result) {
            return $.post("/FinDraT/users/getUsersTypeAhead", {query: query}, function (data) {
                return result(data);
            });
        },
        updater: (item) {
            this.user = item.id;
            return item;
        }
    });
}

I hope I have helped you.

    
answered by 09.11.2017 / 03:27
source
0

Probably because there is no updater function in the version of typeahead.js you are using. Bootstrap recommend using link instead.

Replacing updater is typeahead:selected , is used as follows.

$('.search-user').typeahead({
  source: function (query, result) {
    return $.post("/FinDraT/users/getUsersTypeAhead", {query: query}, function (data) {
      return result(data);
    });
  }
})
.on('typeahead:selected', function(e, item) {
  this.user = item
});
    
answered by 08.11.2017 в 17:46