我正在尝试在vue.js中使用multiple=true设置select的值。当我设置v-model时,一切都是正常的
<select v-model="selected" multiple style="width: 50px;">但是当我设置v-bind:value时,没有在select标签中选择任何值
<select v-bind:value="selected" multiple style="width: 50px;">如何将只读值设置为select?
更新:我在组件中使用了这个,所以不能使用v-model,我必须使用v-bind:value + v-on:change pair。改变功能已经做好了,工作起来就像一个护身符,所以毫无疑问。
发布于 2018-11-28 17:01:37
我不确定,但这可能是一种选择:
new Vue({
el: '#example-6',
data: {
selected: ['A', 'B'],
options: ['A', 'B', 'C']
}
})<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="example-6" class="demo">
<select multiple style="width: 50px;">
<option v-for="option in options" :selected="selected.indexOf (option) != -1">{{option}}</option>
</select>
<br>
<span>Selected: {{ selected }}</span>
</div>
发布于 2020-05-13 00:22:17
我也有同样的问题。我花了几个小时寻找一个转发值和事件的解决方案。
我开始了阅读源代码的研究,我发现了一些有趣的东西。使用v-model时,vue.js会生成a piece of code at runtime。这些代码回退事件以简化赋值。
当select不是多个,但问题仍然存在时,这就挽救了我的生命。我想对于属性值的绑定也有类似的东西,但我没有找到它。如果有人有,我很有兴趣知道它的来源。
最后我找到了一个简单的解决方案。其目的只是转发select (绑定值和输入事件)的v模型交互。我用以下命令创建了一个组件:
model。prop值。这样,我们就可以通过setter利用生成的代码段,因为传递的值就是精化值。getter不需要更复杂。
{
props: ["value"],
computed: {
model: {
get: () => {
// value is a prop of the component
return this.value;
},
set: (valueSelect) => {
this.$emit("input", valueSelect);
}
}
}
}模板:
<template>
<select v-model="model">
<slot></slot>
</select>
</template>我希望这能有所帮助。
很抱歉使用了语法,但我是用Typescript编写组件的,所以它真的不一样。我在这里用typescript和sfc语法编写。
<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Prop, Watch } from "vue-property-decorator";
@Component
export default class SelectComponent extends Vue {
@Prop({
required: true
})
private value: any[] | any;
@Prop({
default: false
})
private multiple: boolean;
private get model() {
return this.value;
}
private set model(value) {
this.$emit("input", value);
}
}
</script>
<template>
<select v-model="model" :multiple="multiple">
<slot></slot>
</select>
</template>发布于 2018-11-28 16:01:35
我认为你想做的是:
<div id="example-6" class="demo">
<select multiple disabled v-model="selected" style="width: 50px;">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<br>
<span>Selected: {{ selected }}</span>
</div>v-model实际上在幕后使用v-bind。如果只使用v-bind,就会缺少输入事件处理,并且对输入的任何更改都不会传播到状态。
更新:
使用v-bind:value,只能选择一个选项:
v-bind:value="selected[0]" // in the select tag你也可以这样做:
<div id="example-6" class="demo">
<select multiple disabled style="width: 50px;">
<option :selected="selected[0]">A</option>
<option :selected="selected[1]">B</option>
<option :selected="selected[2]">C</option>
</select>
<br>
<span>Selected: {{ selected }}</span>
</div>这里有一种更优雅的方式:
<div id="example-6" class="demo">
<select multiple disabled style="width: 50px;">
<option v-for="(option, index) in options" :selected="selected[index]">
{{ option }}
</option>
</select>
<br>
<span>Selected: {{ selected }}</span>
</div>https://stackoverflow.com/questions/53514491
复制相似问题