<template>
<multiselect
v-model="selected"
@input="updateSelected"
:options="phoneTypeOption"
label="title"
track-by="type"
:searchable="false"
:multiple="false"
:taggable="false"
selectLabel=""
deselectLabel=""
selectedLabel=""
placeholder="請選擇"
>
</multiselect>
</template>
<script>
import Multiselect from "vue-multiselect";
export default {
data() {
return {
selected: [],//選中的值,option 的值是數(shù)組對象嚼黔,selected就必須是[]
//下拉選項的option值链快,我這里使用的是數(shù)組對象凉敲,所有必須配置下面的兩個屬性
// label="title" track-by="type"這兩個值對應option的title和type
phoneTypeOption:[
{title:"百度",type:1},
{title:"Google",type:2}
]
}
},
created() {
//通過生命周期添加option的默認值
let option = {
title:"百度",
type:1
};
this.selected.push(option);
},
components: {
Multiselect
}
};
</script>
//樣式要引入着倾,可以全局,也可以局部劲绪∧锌撸看個人
<style src="vue-multiselect/dist/vue-multiselect.min.css"></style>
解釋一下:
- 關(guān)于option和v-model綁定的值用法。有2種:
1.1 是數(shù)組:option = ["百度","Google"]贾富,selected = ""歉眷,
1.2 是數(shù)組對象:option = [{title:"百度",type:1},{title:"Google",type:2}],selected = []颤枪。 - 關(guān)于設(shè)置默認值汗捡。
如果使用的是1.1,那使用生命周期畏纲,直接賦值:
created() {
this.selected = "百度";
}
如果使用的是1.2扇住,那使用生命周期,賦值如下:
created() {
let option = {
title:"百度",
type:1
};
this.selected.push(option);
}
- multiselect的屬性
3.1 @input 是選中事件的回調(diào)盗胀,有返回值艘蹋;updateSelected是自定義方法
methods: {
updateSelected(value) {
//value 自定義參數(shù)接收返回值
console.log("當前選中的值:",value);
}
}
3.2 options 是下拉選項值
3.3 label options的值是數(shù)組對象時使用,label是顯示選項名稱票灰,值為字符串
3.4 track-by options的值是數(shù)組對象時使用女阀,track-by是顯示選項的key,值為數(shù)字
3.5 searchable 是否可以搜索 Boolean值
3.6 multiple 是否多選 Boolean值
3.7 taggable 是否可標記 Boolean值
3.8 selectLabel 點擊當前選項的提示 值為字符串
3.9 deselectLabel 刪除當前選項的提示 值為字符串
3.10 selectedLabel 選中的提示 值為字符串
3.11 placeholder 提示占位符 值為字符串
5,7,8,9,10這幾個屬性因情況而使用米间,大部分情況是不需要使用的强品,至于什么時候用,視情況而定屈糊。