[英]Error in Vue2 Component Method Yet Works When Called From the Console
我有一个Bootstrap模式,可以在Vue方法上显示自己:
methods: {
showAddSongModal() {
$('#addSongModal').modal('show');
}
}
这在方法是根Vue实例的项目中有效。 但是,我现在试图在Vue组件中使用此模式和方法。 该方法由@click="showAddSongModal()
调用,但是当将其放入组件中时,单击时会出现此错误:
Uncaught TypeError: $(...).modal is not a function
否则,该页面将在Chrome Dev Tools中正确加载。 而且,键入$('#addSongModal').modal('show');
在控制台上的行为应为-模态工作!
到目前为止,我检查了:
@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>
笔有效,但是在我的实际项目中$('#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
,Uncaught TypeError消失了。
在组件中,模板中只能有一个根元素。 您需要做的是将按钮和模式包装在单个div(或其他元素)中,组件将正常工作。
在失败的代码笔中将模板更改为此。
<div>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary mt-3 ml-3" @click="showAddSongModal()">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="addSongModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" v-text="message"></div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</div>
工作版本 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.