【发布时间】:2020-10-03 12:49:56
【问题描述】:
我对 Vue.js 比较陌生,正在尝试基于此 custom select menu 创建一个 Vue 组件,并希望为每个列表项添加一个离子图标。
通常,我可以在 Vue.js 中使用以下行创建图标(使用相关的导入图标):
<component class="icon" :is="name-of-icon"></component>
但是,我尝试复制的自定义选择菜单隐藏了默认的 select 元素,并使用自定义 CSS 样式动态添加了自己的元素。
因此,以下不是解决方案,因为它要求我使用默认的select 样式:
<option v-for="option in options" :value="option">
<component class="icon" :is="icon"></component
<p>{{ option }}</p>
</option>
相反,我尝试在设置样式时使用 jQuery 添加图标。将上述笔中的 jQuery 放入方法中,style():
<template>
<select>
<option v-for="option in options" :value="option">
{{ option }}
</option>
</select>
</template>
<script>
import MdPersonIcon from 'vue-ionicons/dist/md-person.vue'
export default {
name: 'custom-select',
components: {MdPersonIcon},
methods: {
style() {
$('select').each(function () {
// rest of code from pen here
for (let i = 0; i < numberOfOptions; i++) {
let option = $('<li />', {
rel: $this.children('option').eq(i).val()
});
let text = $this.children('option').eq(i).text();
let $icon = $('<component>', {
'class': 'icon',
':is': 'md-person-icon',
});
let $label = $('<p>', {
text: text
});
$icon.appendTo(option);
$label.appendTo(option);
option.appendTo($list);
}
// rest of code from pen here
});
}
},
mounted() {
this.style();
}
}
</script>
<style>
/* rest of CSS from the pen here */
.icon {
padding: 8px 8px 8px 0;
margin: 0;
}
</style>
以及组件的用法(其中options 是一个字符串数组):
<custom-select :options="options"></custom-select>
正常创建一个图标,然后检查它会产生如下内容:
<div class="ion profile-icon" data-title="Md Person Icon" data-name="md-person-icon" data-v-fc38bec4="">
<svg viewBox="0 0 512 512" class="ion__svg">
<path d="some long string"></path>
</svg>
</div>
该组件已替换为离子图标。但是,检查元素显示该组件没有被替换:
<component class="icon" :is="md-person-icon"></component>
我不太清楚为什么会这样。
我知道我应该不尝试混合使用 jQuery 和 Vue,但我目前想不出另一种方法来创建自定义选择菜单 Vue 组件。
【问题讨论】:
标签: javascript jquery vue.js vuejs3