[Vuejs]-Fill materialize autocomplete component with vue variable

1👍

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

Leave a comment