Vue js:多选项选择

时间:2016-11-16 11:01:08

标签: javascript vue.js

目标:选择选择标记的多个选项。

尝试documentation说:要实现多选输入,使用v-model绑定的属性应为数组。

错误: [Vue警告]:需要一个Array值来绑定它,但是得到了String。

绑定到(multipleSelections)的值是一个数组,所以这是什么原因?

这是jsfiddle

脚本:

new Vue({
el:'#app',
data: function() {
  return {
      multipleSelections: ["Mr Potato (Manager)"],
      data: null,
      multiple: "true",
      assets:["Mr Potato (Manager)", "Mr Blade (Manager)", "Mrs Spice (Manager)"]
    }
  },
  created() {
    console.log("selections: ",this.multipleSelections);
  }
});

HTML:

<script src="https://unpkg.com/vue@2.0.6/dist/vue.js"></script>
<div class='container' id='app'>
  <h2>{{"title".toUpperCase()}}</h2>
  <p class='center help-text' v-if="multiple === 'true'">(Use ctrl or cmd to select multiple)</p>
  <select
    :multiple="multiple === 'true'"
    v-bind:class="{ 'fix-height': multiple === 'true' }"
    v-model="multipleSelections"
   >
    <option
      v-for="asset in assets"
      :value="asset">
      {{asset}}
    </option>
  </select>
{{ multipleSelections }}

2 个答案:

答案 0 :(得分:1)

在选择作品中给予multiple="true"。这是jsfiddle link

 <select
      multiple="true"
      v-bind:class="{ 'fix-height': multiple === 'true' }"
      v-model="multipleSelections"
      >

答案 1 :(得分:-1)

如果您正在寻找功能齐全的东西,我发现此插件可以解决问题。它还具有出色的文档(请参见下面的链接)。

https://vue-multiselect.js.org/

安装库之后,直接从文档中查看示例: https://vue-multiselect.js.org/#sub-getting-started

<!-- Vue component -->
<template>
  <div>
    <multiselect v-model="value" :options="options"></multiselect>
  </div>
</template>

<script>
  import Multiselect from 'vue-multiselect'

  // register globally
  Vue.component('multiselect', Multiselect)

  export default {
    // OR register locally
    components: { Multiselect },
    data () {
      return {
        value: null,
        options: ['list', 'of', 'options']
      }
    }
  }
</script>

<!-- New step!
     Add Multiselect CSS. Can be added as a static asset or inside a component. -->
<style src="vue-multiselect/dist/vue-multiselect.min.css"></style>

<style>
  your styles
</style>