我有一个 Bootstrap 模式,可以在此 Vue 方法上显示自己:
methods: {
showAddSongModal() {
$('#addSongModal').modal('show');
}
}
这适用于方法为根 Vue 实例的项目。但是,我现在尝试在 Vue 组件中使用此模式和方法。该方法由 @click="showAddSongModal()
调用,但当将其放入组件内时,我在单击时收到此错误:
Uncaught TypeError: $(...).modal is not a function
否则,页面在 Chrome 开发工具中加载时不会出现错误。更重要的是,在控制台输入 $('#addSongModal').modal('show');
的行为就像它应该的那样 - 模态有效!
到目前为止,我检查过:
- jQuery 仅被调用一次。
- jQuery、Bootstrap、Vue、Axios 等。在我的 Vue 组件之前调用。
@click="showAddSongModal()
从控制台运行的事实应该验证我的构建过程,对吗?
为什么此模式和方法可以在根 Vue 实例中工作,但在放置在 Vue 组件内时会导致 Uncaught TypeError
?
我的项目有 Vue 组件,每个组件都在一个组件文件中,如下所示:
<template>
<div class="song-table">
<song-modal-form></song-modal-form>
<div class="table-header d-flex justify-content-between align-items-center mt-3">
<form id="search" class="">
Search <input name="query" v-model="filterKey">
</form>
....
html continues
<script>
import SongModalForm from './SongModalForm.vue';
export default {
components: {
SongModalForm
},
....
methods: {
showAddSongModal() {
console.log('HELP!');
$('#addSongModal').modal('show');
},
....
</script>
This Pen shows the scenario, a parent component calling the child component with the modal.
笔可以工作,但在我的实际项目中 $('#addSongModal').modal('show');
只能从控制台工作,不能从组件工作:
最佳答案
我在这个项目中使用 Laravel 5.4.14 框架。使用 webpack,我将 .js 文件混合在一起,如下所示:
将整个站点范围内所需的 .js 文件(JQuery、Bootstrap、Vue 等)合并到一个
app.js
特定于后端的 .js 文件,例如我的 Vue 实例和
backend.js
中的专用脚本
app.js
只有以下一行需要 bootstrap.js:
require('./bootstrap');
需要 bootstrap.js
(JQuery、Bootstrap、Vue 等)。
backend.js
看起来像这样:
import SpecialComponent from './components/SpecialComponent.vue';
import LoginModal from './components/LoginModal.vue';
import RegisterModal from './components/RegisterModal.vue';
import SongTable from './components/SongTable.vue';
Vue.config.ignoredElements = [
'wave'
];
const app = new Vue( {
el: '#app-backend',
components: {
SpecialComponent ,
LoginModal,
RegisterModal,
SongTable
},
data: {
currentPath: window.location.pathname
},
});
然后对于后端页面,html 会像这样调用文件:
<script src="js/app.js"></script>
<script src="js/backend.js"></script>
这不起作用。
一旦将 require('./bootstrap');
添加到 backend.js
中,并且我删除了 app.js
,即未捕获的类型错误走了。
关于javascript - Vue2 组件方法中出现错误,但从控制台调用时仍有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42541237/