如何在Vue.js中显示组件/创建/加载页面的模态



我是Vue.js的新手,在模态方面很吃力。我想在用户导航到某个组件时首先加载模态窗口。我试图创建一些示例模态,如果我单击一个按钮并触发$('#modalId').modal('show'),它就会打开。但是,当我尝试从Vue的created () {...}执行相同的命令时,它不会打开模式窗口。我不想点击按钮打开模式窗口,我想在页面/组件加载时打开。

<!-- This works fine -->
<button class="btn btn-dark" @click="openModal" data-target="#loginModal">Open modal</button>
<!-- MODAL -->
<div class="modal" ref="modal" id="loginModal" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Insert required data</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control">
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-dismiss="modal">Submit</button>
<a href="#" @click="logout" data-dismiss="modal">
<span>{{ $t('pages.userIconInHeader.signOut') }}</span>
</a>
</div>
</div>
</div>
</div>
...
export default {
name: 'test',
data () {
return {}
},
created () {
// HERE I WOULD LIKE TO OPEN MODAL. If it's even possible?
$(document).ready(function () {
this.openModal()
})
},
methods: {
openModal () {
$('#loginModal').modal('show')
},
...

在不带$(document).ready(function(){}):的mounted中使用

mounted() {
this.openModal();
},
不要混合jQuery和Vue。Vue使用虚拟DOM,您应该根据Vue文档更新、显示和隐藏元素,而不是使用jQuery。这是一篇关于在Vue中创建模态的文章,我希望它能有所帮助https://alligator.io/vuejs/vue-modal-component/
mounted() {
this.showModal()
},
methods: {
showModal() {
this.$modal.show("model-name")
},
}

这可以用于在vuejs 中打开模型

最新更新