首页 > AI文库 >

封装一个可以在父组件用v-model的原生select组件

来自 上海市上海市 的网友分享 (°C) 13442

来自 上海市上海市 的网友 分享

(°C)

首先,我们需要创建一个自定义的原生Select组件,然后在父组件中使用v-model进行双向绑定。

1. 创建自定义Select组件(CustomSelect.vue):

```html
<template>
<select :value="value" @change="onChange">
<option v-for="(option, index) in options" :key="index" :value="option.value">
{{ option.label }}
</option>
</select>
</template>

<script>
export default {
props: {
value: {
type: [String, Number],
required: true
},
options: {
type: Array,
default: () => []
}
},
methods: {
onChange(event) {
this.$emit('input', event.target.value);
}
}
};
</script>
```

2. 在父组件中使用自定义Select组件(ParentComponent.vue):

```html
<template>
<div>
<custom-select v-model="selectedValue" :options="options"></custom-select>
</div>
</template>

<script>
import CustomSelect from './CustomSelect.vue';

export default {
components: {
CustomSelect
},
data() {
return {
selectedValue: '',
options: [
{ label: '选项1', value: '1' },
{ label: '选项2', value: '2' },
{ label: '选项3', value: '3' }
]
};
}
};
</script>
```

这样,我们就创建了一个可以在父组件用v-model的原生select组件。

相关推荐

那只歇着的手

高中作文

安全工作讲话稿

投稿专栏

中国经济实现高质量发展具备哪些显著优势论文1500字

AI文库

科学管理之父泰勒在美国国会听证会上讲话的主要内容

AI文库

请用 1、6、6、8四个数字算24点

AI文库

热门图文

上一篇:请同学们思考世界变革动荡持续演进会对中国人民的生活造成什么影响?

下一篇:中国经济实现高质量发展具备那些优势