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.
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:
Create an empty object
var data = {};
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;
}
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);
});