简体   繁体   English

用于选择的 Vue.js 选项组件

[英]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模板语法错误不能在有状态组件根元素上使用 v-for,因为它呈现多个元素

How could I create this kind of component?我怎样才能创建这种组件? I'm using vue 2.0.5我正在使用 vue 2.0.5

Here are some relevant docs: https://v2.vuejs.org/v2/guide/components.html#DOM-Template-Parsing-Caveats以下是一些相关文档: https ://v2.vuejs.org/v2/guide/components.html#DOM-Template-Parsing-Caveats

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/这是 JSFiddle: https ://jsfiddle.net/zL6woLa2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM