ibeautiful
2023-04-14 17:19:07
我對 Vue.js 比較陌生,試圖基于此自定義選擇菜單創建一個 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(); } }該組件已替換為 ionicon。但是,檢查元素顯示組件未被替換:<component class="icon" :is="md-person-icon"></component>我不太清楚為什么會這樣。我知道我不應該嘗試混合使用 jQuery 和 Vue,但我目前想不出另一種方法來創建自定義選擇菜單 Vue 組件。
1 回答

哆啦的時光機
TA貢獻1779條經驗 獲得超6個贊
您必須將 jQuery 創建的元素傳輸到 Vue,因為 jQuery 在運行時添加的內容不會綁定并且 Vue 無法檢測到,這是我看到您的 jquery 代碼正在執行的示例
<template>
<ul>
<li for="option in options" :key="option.rel" :rel="option.rel">
<component class="icon" :is="option.icon" />
<p>{{ option.text }}</p>
</li>
</ul>
</template>
<script>
export default {
data(){
return {
options:[
{rel:'hide', text:'-- Month --', icon: 'md-person-icon'},
{rel:'january', text:'january', icon: 'md-person-icon'},
{rel:'february', text:'february', icon: 'md-person-icon'},
...
],
}
}
}
</script>
添加回答
舉報
0/150
提交
取消