DEV Community

Raymond Camden
Raymond Camden

Posted on • Originally published at raymondcamden.com on

Datalists with Vue.js

This isn't necessarily a very exciting post, but a few days back someone asked me about integrating Vue.js with datalist tags. The datalist tag is one of my favorite HTML tags and something I've blogged about a few times in the past. If you aren't familiar with it, it basically provides a "autosuggest" style experience to an input tag.

The HTML is pretty simple. Here is the example used in the MDN article I linked to above:

<label for="myBrowser">Choose a browser from this list:</label>
<input list="browsers" id="myBrowser" name="myBrowser" />
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Internet Explorer">
  <option value="Opera">
  <option value="Safari">
  <option value="Microsoft Edge">
</datalist>
Enter fullscreen mode Exit fullscreen mode

Basically - you create a <datalist> element and supply options. You then take your input and add the list="id of the list" attribute. Now when the user types, they will get suggestions based on the list and what they've typed in. It's pretty well supported (basically everyone but Safari and Mobile Safari, because of course) and fails gracefully (the user can still type anything they want). How would you combine this feature with Vue.js? Let's look at a static example. First, the HTML:

<div id="app">
  <input type="text" v-model="film" list="films">
  <datalist id="films">
    <option v-for="film in films">{{film}}</option>
  </datalist>
</div>
Enter fullscreen mode Exit fullscreen mode

You can see the input field and the list. The option tag is tied to a variable called films. Now let's look at the JavaScript:

const app = new Vue({
  el:'#app',
  data() {
    return {
      film:'',
      films:[
        "A Throne Too Far",
        "The Cat Wasn't Invited",
        "You Only Meow Once",
        "Catless in Seattle"
        ]
    }
  }
})
Enter fullscreen mode Exit fullscreen mode

Not too exciting, but it works rather well. You can test it below:

How would you make it dynamic? Simple - just change how the data is generated. Here's an example of that:

const app = new Vue({
  el:'#app',
  data() {
    return {
      film:'',
      films:[]
    }
  },
  created() {
    fetch('https://swapi.co/api/films/')
    .then(res => res.json())
    .then(res => {
      this.films = res.results.map(f => {
        return f.title;
      })
    })
  }
})
Enter fullscreen mode Exit fullscreen mode

All I did was add in a created event handler and hit the Star Wars API for my data. You can test the result below:

I may be biased - but everything is better in Vue.

Top comments (0)