是否可以从组件外部调用方法以使组件可重用?
现在,我添加我的按钮以在模板插槽中打开模态:
index.php
<modal>
<template slot="button">
<button class="btn">Open modal</button>
</template>
Some modal text
</modal>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
我觉得有更好的选择,但我不知道。
是的,您可以从组件外部调用方法!
父组件
<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>
Run Code Online (Sandbox Code Playgroud)
子组件
<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>
Run Code Online (Sandbox Code Playgroud)
当然,接受模态组件的属性:
props: ['open']
Run Code Online (Sandbox Code Playgroud)
然后传入:
<modal :open="boolToOpenModal"> ... </modal>
Run Code Online (Sandbox Code Playgroud)
然后:
<div v-if="showingModal || open"><slot></slot></div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7621 次 |
| 最近记录: |