用vue 写一个原生select ,宽度为100px,高度为50px,背景颜色红色,字体白色,异步渲染,有默认选项,选择提示
时间: 2024-02-20 13:56:23 浏览: 21
好的,以下是一个简单的 Vue 原生 select 组件的代码:
```vue
<template>
<div class="custom-select" :style="{ width: '100px', height: '50px', backgroundColor: 'red', color: 'white' }">
<div class="selected-item" @click="toggleOptions">{{ selectedText }}</div>
<div class="options" v-if="showOptions">
<div class="option" v-for="(option, index) in options" :key="index" @click="selectOption(option)">
{{ option.text }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showOptions: false,
selectedOption: null,
options: [
{ value: '1', text: 'Option 1' },
{ value: '2', text: 'Option 2' },
{ value: '3', text: 'Option 3' }
]
};
},
computed: {
selectedText() {
return this.selectedOption ? this.selectedOption.text : 'Select an option';
}
},
methods: {
toggleOptions() {
this.showOptions = !this.showOptions;
},
selectOption(option) {
this.selectedOption = option;
this.showOptions = false;
alert(`You selected ${option.text}`);
}
}
};
</script>
```
这个组件有以下特点:
- 宽度为 100px,高度为 50px。
- 背景颜色为红色,字体颜色为白色。
- 异步渲染,即只有当用户点击选择框时才会渲染选项列表。
- 有默认选项,即在用户没有选择任何选项时,默认显示 "Select an option"。
- 选择后会有提示,即弹出一个提示框告诉用户选择了哪个选项。