vue.js - 如果我只有选项属性,如何在 vue-multiselect 中设置默认值?
问题描述
我有一个选项数组,它显示在多选选项中。但我需要选择一个提供 id 的默认选项。在我的代码中,我需要选择 id = 2 的默认选项。如何在 vue.js 中使用多选来做到这一点?
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-multiselect@2.1.0"></script>
<link rel="stylesheet" href="https://unpkg.com/vue-multiselect@2.1.0/dist/vue-multiselect.min.css">
<div id="vue-app2">
<div>
<label class="typo__label">Single select / dropdown</label>
<multiselect v-model="value" deselect-label="Can't remove this value" track-by="id" label="name"
placeholder="Select one" :options="options" :searchable="false" :allow-empty="false">
<template slot="singleLabel" slot-scope="{ option }"><strong>{{ option.name }}</strong> is written
in<strong> {{ option.language }}</strong></template>
</multiselect>
<pre class="language-json"><code>{{ value }}</code></pre>
</div>
</div>
<script >
Vue.component('multiselect', window.VueMultiselect.default);
new Vue({
el: '#vue-app2',
data: {
id:2,
value:null,
options: [
{ id:1, name: 'Vue.js', language: 'JavaScript' },
{ id:2, name: 'Rails', language: 'Ruby' },
{ id:3,name: 'Sinatra', language: 'Ruby' },
{ id:4,name: 'Laravel', language: 'PHP', $isDisabled: true },
{ id:5,name: 'Phoenix', language: 'Elixir' }
]
}
});
</script>
解决方案
如果您需要从数据中获取默认值 id,则在mount 上查找并设置默认值;
new Vue({
el: '#vue-app2',
data: {
id: 2,
value: null,
options: [
{ id: 1, name: 'Vue.js', language: 'JavaScript' },
{ id: 2, name: 'Rails', language: 'Ruby' },
{ id: 3, name: 'Sinatra', language: 'Ruby' },
{ id: 4, name: 'Laravel', language: 'PHP', $isDisabled: true },
{ id: 5, name: 'Phoenix', language: 'Elixir' }
]
},
mounted() {
this.value = this.options.find(option => option.id === this.id);
}
});
推荐阅读
- amazon-web-services - Spinnaker 创建应用程序
- azure-devops - 不能再创建和编辑服务挂钩
- python - Python 软件开发中的 stdafx.h 等价物
- string - 将 STR、FLOAT 或 ATTR 组合到 Tableau 中的计算字段中
- sql - 如果 Linq 中的值不为空,则仅包含在 where 条件中
- arduino - 如何在没有计算机的情况下仅使用数字引脚在 Arduino 上读取键盘输入
- ruby-on-rails - 即使手动一切正常,Rspec 测试也会失败
- typescript - 创建一个 TypeScript 记录,其中第二个类型参数取决于第一个?
- javascript - 无法使用三星 AVPlay API 更改播放头位置
- javascript - React 中的状态变化动画