Search code examples
vue.jsdatalist

Datalist disapearing in a simple vue example


Try to select from datalist while a data property is updated on a interval.

What is wrong in my code?

http://jsfiddle.net/startflorin/gr6b1h7j/18

Mounted intervals:

setInterval((ctx) => { ctx.notification = "111"; }, 500, this);
setInterval((ctx) => { ctx.notification = "222"; }, 500, this);

Data:

data: {
    notification: null,
    demoList:[
        {
            id: 1,
            name: "option 1",
        },
        {
            id: 2,
            name: "option 2",
        },
        {
            id: 3,
            name: "option 3",
        },
    ],
},

My HTML code:

<div>
    {{ notification }}
</div>

<input list='demoList' v-on:change="selectSymbolList(target.value)">

<datalist id="demoList">
    <option v-for="item in this.demoList" v-bind:value="item.name" v-bind:key="item.id">{{ item.name }}</option>
</datalist>

Solution

  • To cache the rendering of <input> and <datalist> (to isolate them from unrelated changes in the component's template), put them into a component:

    Vue.component('demo-list', {
      props: ['items'],
      template: `<div>
        <input list='demoList'>
        <datalist id="demoList">
          <option v-for="item in items" v-bind:value="item.name" v-bind:key="item.id">{{ item.name }}</option>
        </datalist>
      </div>`
    })
    

    Note this example requires the runtime compiler to compile the template string. Otherwise, render functions would be required instead of template.

    Then use the component in your app's template:

    <div id="app">
      <div>{{ notification }}</div>
    
      <demo-list :items="demoList"></demo-list>
    </div>
    

    demo