如何在纯HTML页面使用vue-select?运行报错如何排查
问题背景
首次尝试使用Vue + vue-select开发,按照浏览器端引入说明导入相关资源后,编写了如下HTML测试页面:
<!DOCTYPE html> <html lang="en"> <head> <!-- 优先引入VueJS --> <script src="https://unpkg.com/vue@latest"></script> <!-- 引入vue-select资源 --> <script src="https://unpkg.com/vue-select@latest"></script> <link rel="stylesheet" href="https://unpkg.com/vue-select@latest/dist/vue-select.css" /> </head> <body> <div id="app"> <h1>Vue Select</h1> <v-select :options="options"></v-select> </div> <script> Vue.component("v-select", VueSelect.VueSelect); new Vue({ el: "#app", data: { options: ["foo", "bar", "baz"], }, }); </script> </body> </html>
页面运行时浏览器控制台抛出报错,报错信息截图如下:
问题根因
核心问题是版本不匹配:
https://unpkg.com/vue@latest当前默认拉取的是Vue 3.x版本,但代码中使用的new Vue()实例初始化、Vue.component()全局组件注册都是Vue 2.x的专属语法,Vue 3已经废弃了这套编写方式。- 同时
https://unpkg.com/vue-select@latest默认拉取的是v3.x稳定版,这个版本仅兼容Vue 2.x,无法在Vue 3环境下正常运行。
修复方案
根据实际技术选型选择对应方案即可:
- 方案1:使用Vue 2 + vue-select v3稳定版(适合入门学习,和现有示例代码语法完全兼容)
仅需要把Vue的引入地址从https://unpkg.com/vue@latest修改为固定指向Vue2版本的地址https://unpkg.com/vue@2,其余代码无需改动,刷新页面即可正常运行。 - 方案2:使用Vue 3 + 适配Vue3的vue-select v4版本
需要同时调整vue-select的引入版本和Vue初始化逻辑,修正后的可运行代码如下:
<!DOCTYPE html> <html lang="en"> <head> <!-- 引入Vue3 --> <script src="https://unpkg.com/vue@3"></script> <!-- 引入适配Vue3的vue-select v4版本 --> <script src="https://unpkg.com/vue-select@4"></script> <link rel="stylesheet" href="https://unpkg.com/vue-select@4/dist/vue-select.css" /> </head> <body> <div id="app"> <h1>Vue Select</h1> <v-select :options="options"></v-select> </div> <script> const app = Vue.createApp({ data() { return { options: ["foo", "bar", "baz"] } } }) app.component("v-select", VueSelect.VueSelect); app.mount("#app"); </script> </body> </html>
入门阶段优先选择方案1,目前公开的基础教程、问题解决方案大多基于Vue2 + vue-select v3编写,学习过程中排查问题、查找参考资料更方便。
内容的提问来源于stack exchange,提问作者Dom
相关产品推荐
相关产品推荐

