Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js option component for select

I'm trying to create this component:

<template>
  <option v-for="(text, value) in options" :value="value">
    {{ text }}
  </option>
</template>

But I get this error message:

template syntax error Cannot use v-for on stateful component root element because it renders multiple elements

How could I create this kind of component? I'm using vue 2.0.5

Here are some relevant docs: https://v2.vuejs.org/v2/guide/components.html#DOM-Template-Parsing-Caveats

like image 602
Neves Avatar asked Sep 14 '26 15:09

Neves


1 Answers

You can't do that inside a component, you need one top level element so you're going to need to wrap that in a select and have the entire select box as your component. You will then need to pass any options as props, so:

Template:

<template id="my-select">
  <select>
    <option v-for="(text, value) in options" :value="value">
      {{ text }}
    </option>
  </select>
</template>

Component:

Vue.component('my-select', {
  props: ['options'],
  template: "#my-select"
});

View Model:

new Vue({
  el: "#app",
  data: {
    options: {
      "1": "foo",
      "2": "bar",
      "3": "baz"
    }
  }
});

Now in your root page, just pass the options as a prop:

<my-select :options="options"></my-select>

Here's the JSFiddle: https://jsfiddle.net/zL6woLa2/

like image 151
craig_h Avatar answered Sep 17 '26 05:09

craig_h



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!