我有以下简单的设置,以及使用 Vue 3 的客户端 JavaScript 应用程序:
HTML(带有选择框):
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="vuetest">
<select id="assignment-select" v-model="ft_assignment">
<optgroup v-for="optgroup in ft_assignments" :label="optgroup.text">
<option
v-for="option in optgroup.children"
:value="option.id"
:disabled="option.disabled"
>
{{ option.text }}
</option>
</optgroup>
</select>
</div>
<script type="module">
import { createApp } from "https://unpkg.com/vue@3/dist/vue.esm-browser.js";
const app = createApp({
data() {
return {
ft_assignment: "a",
ft_assignments: [
{
text: "hi",
children: [
{ id: "a", text: "a1" },
{ id: "b", text: "b1" },
],
},
{
text: "there",
children: [
{ id: "c", text: "c1" },
{ id: "d", text: "d1" },
],
},
],
};
},
watch: {
ft_assignment(v) {
console.log(v);
},
},
}).mount("#vuetest");
</script>
</body>
</html>
我想使用具有搜索等现代功能的“漂亮”选择框(例如 vue-select 或 select2) - 但我不知道如何包含相关组件。我看到许多关于混合 jQuery 和 Vue.js 的警告,因此我避免只将 select2 作为 jquery 插件并以这种方式呈现。
如何将选择框变成“更好”更现代的选择元素?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果您不想使用插件而更喜欢自己构建它(我喜欢这样做)。
为此,您可以创建一个包含输入类型文本的 div,您可以使用该文本搜索 div 内的选项。这些选项作为锚标记存储在隐藏的 div 中。然后,将事件侦听器附加到锚标记元素及其需要调用的函数。
看看这个,您当然可以编辑它并使其按照您需要的方式工作。
这不是使用vue 3的esm构建,但仍然使用浏览器中直接支持的UMD构建(原因是vue-select库不提供esm构建版本,但它仍然支持UMD构建)。
基本上以这种方式包含依赖项:
然后这样导入
vue:const { createApp } = Vue;然后以这种方式导入
vue-select组件:const app = createApp({ components: { vSelect: window["vue-select"], }, ...工作代码片段: