javascript - VueJS + jQuery:在 Vue.js 中动态创建组件
问题描述
我对 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();
}
}
</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 组件。
解决方案
您必须将 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>
推荐阅读
- python - 将一个df的值与第二个df的第一个值连接和比较,然后进行累积比较
- flutter - 被调用的构造函数不是 const 构造函数。尝试从构造函数调用中删除“const”。颤振如何解决?
- python - Pymongo代码可以在需要用户名和密码才能注册的网站页面上快速循环大量帐户?
- docker - Docker-Compose - 在主机网络上给容器一个 IP,并允许容器到容器的连接和主机网络连接
- sink - 对 R 接收器的 pyper 调用创建输出文件但什么也不写
- django - 为什么在运行 Django TestCase 时没有创建对象
- sql - 如何在配置单元中将字符串转换为数组?
- string - '或' 在用户输入后如果有条件,则不使用字符串
- react-native - 反应原生标题左按钮左边距
- python-3.x - 如何从熊猫数据框中删除转义字符(反斜杠“\”)