可以从vue组件外部打开模态 [英] Possible to open modal from outside the vue component
本文介绍了可以从vue组件外部打开模态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以从组件外部调用方法以使组件可重复使用?
Is it possible to call a method from outside the component to make the component reuseable?
现在我添加我的按钮以在模板槽中打开模式:
Right now I add my button to open the modal in a template slot:
index.php
<modal>
<template slot="button">
<button class="btn">Open modal</button>
</template>
Some modal text
</modal>
Modal.vue
<template>
<div>
<div @click="showModal"><slot name="button"></slot></div>
<div v-if="showingModal"><slot></slot></div>
</div>
</template>
<script>
export default {
data () {
return {
showingModal: false,
}
},
methods: {
showModal() {
this.showingModal = true;
},
}
}
</script>
我觉得有更好的选择,但我无法理解。
I feel like there is an better option but I can't figure it out.
推荐答案
是的,您可以从组件外部调用方法!
Yes,you can call a method from outside the component!
父组件
<template>
<div>
<modal ref="modal"></modal>
<button @click="openModal">Open Modal</button>
</div>
</template>
<script>
import modal from './child.vue'
export default {
components: { modal }
methods: {
openModal() { this.$refs.modal.show() }//executing the show method of child
}
}
</script>
子组件
<template>
<div v-if="showModal">
<div id="modal">
<p>Hello i am a modal
</p>
<button @click="hide">Close</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showModal: false
}
},
methods: {
show() {
this.showModal = true
},
hide(){
this.showModal = false
}
}
}
</script>
这篇关于可以从vue组件外部打开模态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文