vue3 setup scss封装下拉框
时间: 2023-07-11 16:45:32 浏览: 97
好的,这里是一个 Vue3 下拉框组件的 SCSS 和 setup 封装示例:
```vue
<template>
<div class="select-wrapper" :class="{ open: isOpen }">
<div class="select-header" @click="toggleOpen">
<span>{{ selected }}</span>
<i class="arrow" :class="{ 'arrow-up': isOpen, 'arrow-down': !isOpen }"></i>
</div>
<div class="select-options">
<div class="option" v-for="(option, index) in options" :key="index" @click="selectOption(option)">
{{ option }}
</div>
</div>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
props: {
options: {
type: Array,
required: true,
},
},
setup(props) {
const isOpen = ref(false);
const selected = ref(props.options[0]);
const toggleOpen = () => {
isOpen.value = !isOpen.value;
};
const selectOption = (option) => {
selected.value = option;
isOpen.value = false;
};
return {
isOpen,
selected,
toggleOpen,
selectOption,
};
},
};
</script>
<style lang="scss" scoped>
.select-wrapper {
position: relative;
width: 200px;
.select-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px;
border: 1px solid #ccc;
cursor: pointer;
span {
flex: 1;
margin-right: 10px;
}
.arrow {
width: 0;
height: 0;
border-style: solid;
border-width: 5px 4px 0 4px;
}
.arrow-down {
border-color: #999 transparent transparent transparent;
}
.arrow-up {
border-color: transparent transparent #999 transparent;
}
}
.select-options {
position: absolute;
top: 100%;
left: 0;
width: 100%;
z-index: 999;
background-color: #fff;
border: 1px solid #ccc;
border-top: none;
max-height: 200px;
overflow-y: auto;
.option {
padding: 10px;
cursor: pointer;
&:hover {
background-color: #f2f2f2;
}
}
}
&.open {
.select-header {
border-bottom: none;
.arrow {
transform: rotate(180deg);
}
}
.select-options {
border-top: 1px solid #ccc;
}
}
}
</style>
```
这个下拉框组件的 SCSS 样式使用了嵌套规则和变量,使得样式更加清晰和易于维护。在组件内部,使用 `isOpen` 和 `selected` 两个响应式变量来控制下拉框的状态和选中的选项。当用户点击下拉框头部时,调用 `toggleOpen` 方法来切换下拉框的状态;当用户点击下拉框中的某个选项时,调用 `selectOption` 方法来更新选中的选项,并关闭下拉框。
你可以在父组件中使用这个下拉框组件,如下所示:
```vue
<template>
<div>
<Select :options="options" />
</div>
</template>
<script>
import Select from './Select.vue';
export default {
components: {
Select,
},
data() {
return {
options: ['Option 1', 'Option 2', 'Option 3'],
};
},
};
</script>
<style lang="scss">
// 全局样式
$primary-color: #409eff;
button {
color: #fff;
background-color: $primary-color;
border: none;
padding: 10px;
border-radius: 4px;
cursor: pointer;
&:hover {
background-color: darken($primary-color, 10%);
}
}
</style>
```
这个父组件将一个包含三个选项的数组传递给下拉框组件,然后将下拉框组件渲染到页面中。你可以根据需要调整下拉框的样式和功能。
阅读全文