Vue项目集成cxlt-vue2-toastr报Uncaught TypeError错误的解决方法
问题解决:Uncaught TypeError: Cannot read properties of undefined (reading 'use')
报错原因
- 当前项目使用Vue3(通过
createApp初始化),但cxlt-vue2-toastr是仅支持Vue2的组件,二者不兼容。 - Vue3不再默认导出
Vue构造函数,import Vue from 'vue'会得到undefined,调用Vue.use自然触发该报错。
解决方案
方案一:改用Vue3兼容的Toastr组件
推荐使用vue-toastification(支持Vue3),步骤如下:
- 安装依赖:
npm install vue-toastification@next
- 修改
app.js代码:
import './bootstrap'; import { createApp } from 'vue'; import CreateCart from './components/CreateCart.vue'; // 导入Vue3版toast组件及样式 import Toast from 'vue-toastification'; import 'vue-toastification/dist/index.css'; const app = createApp({}); app.component('create-cart', CreateCart); // 配置并注册toast const toastConfigs = { position: 'top-right', timeout: 5000, transition: 'Vue-Toastification__fade', newestOnTop: true }; app.use(Toast, toastConfigs); window.axios = require('axios'); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; app.mount('#app');
方案二:切换回Vue2环境(若坚持用cxlt-vue2-toastr)
- 安装Vue2依赖:
npm install vue@2.x
- 修改
app.js为Vue2写法:
import Vue from 'vue'; import './bootstrap'; import CreateCart from './components/CreateCart.vue'; import CxltToastr from 'cxlt-vue2-toastr'; import 'cxlt-vue2-toastr/dist/css/cxlt-vue2-toastr.css' const toastrConfigs = { position: 'top right', showDuration: 2000, timeOut: 5000, } Vue.use(CxltToastr, toastrConfigs) window.axios = require('axios'); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; new Vue({ el: '#app', components: { CreateCart } });
内容的提问来源于stack exchange,提问作者16_018_RHR
相关产品推荐
相关产品推荐

