vue 绑定 chosen v-model
时间: 2023-06-28 15:04:17 浏览: 247
在 Vue 中绑定 chosen 的 v-model,可以使用 Vue 的自定义组件和 v-model 的语法糖。
首先,在你的项目中引入 chosen.js 和 chosen.css 文件。然后,你需要创建一个 Vue 组件来封装 chosen。
```html
<template>
<select :class="classes" :disabled="disabled" ref="select">
<slot></slot>
</select>
</template>
<script>
import $ from 'jquery'
import 'chosen-js'
import 'chosen-js/chosen.css'
export default {
props: {
value: {
type: [String, Number, Array],
default: ''
},
options: {
type: Array,
default: () => []
},
classes: {
type: String,
default: ''
},
disabled: {
type: Boolean,
default: false
}
},
mounted() {
$(this.$refs.select).chosen()
$(this.$refs.select).on('change', this.handleChange)
},
beforeDestroy() {
$(this.$refs.select).off('change', this.handleChange)
$(this.$refs.select).chosen('destroy')
},
methods: {
handleChange() {
this.$emit('input', $(this.$refs.select).val())
}
}
}
</script>
```
这个组件包含了 chosen 的初始化、销毁和值变化事件监听。它接受四个 props:
- value:绑定的值,可以是字符串、数字或数组类型。
- options:下拉选项的数组。
- classes:附加到 select 元素的类名。
- disabled:是否禁用选择框。
接下来,你可以在你的父组件中使用这个组件,并使用 v-model 绑定值:
```html
<template>
<div>
<chosen-select v-model="selectedValue" :options="options"></chosen-select>
<p>Selected value: {{ selectedValue }}</p>
</div>
</template>
<script>
import ChosenSelect from '@/components/ChosenSelect'
export default {
components: {
ChosenSelect
},
data() {
return {
selectedValue: '',
options: ['Option 1', 'Option 2', 'Option 3']
}
}
}
</script>
```
这样,你就可以在父组件中使用 v-model 来绑定选择框的值了。
阅读全文
相关推荐











