Search code examples
jqueryvue.jsautocompletematerialize

Fill materialize autocomplete component with vue variable


i'm using the matarialize autocomplete component and i need to set its data with an array stored in vue.js

       data:{
            param:[]
       },
       mounted(){
            this.init();
            $('input.autocomplete').autocomplete({
                data: {

                },
            });
        },

How can i pass in the jquery function the param variable stored in vue data? This array is filled with JSON data that contains strings from my database.


Solution

  • Ok, so you have your array:

    var countries = ["rome", "london", "new york"];
    

    And we need to transform it into an object, so that the autocomplete can use it, like this:

    data: {
            "Apple": null,
            "Microsoft": null,
            "Google": 'https://placehold.it/250x250'
          },
    

    We do this is three steps:

    1. Create an empty object

      var data = {};
      
    2. Loop over the countries array and create a key value pair for each in the data object. Note we use 'null' as the value unless we are using images.

      for (const key of countries) {
        data[key] = null;
      }
      
    3. Finally, set data to be equal to this new object (which I've also named data)

      var options = {
         data: data
      }
      

    When you initialize the autocomplete, we pass the data through the options object:

       var instances = M.Autocomplete.init(elems, options);
    

    Working codepen here.

    Full code:

    document.addEventListener('DOMContentLoaded', function() {
    
        var elems = document.querySelectorAll('.autocomplete');
    
        var countries = ["rome", "london", "new york"];
    
        var data = {};
    
        for (const key of countries) {
              data[key] = null;
        }
    
        var options = {
          data: data
        }
    
        var instances = M.Autocomplete.init(elems, options);
    
      });
    

    https://materializecss.com/autocomplete.html