在父组件中使用 Vue 模态组件



我正在用 Vue 构建简单的模态组件。我想在父组件中使用此组件,并能够从父组件切换它。

这是我现在的模态组件代码:

<script>
export default {
	name: 'Modal',
	data() {
		return {
			modalOpen: true,
		}
	},
	methods: {
		modalToggle() {
			this.modalOpen = !this.modalOpen
		},
	},
}
</script>
<template>
	<div v-if="modalOpen" class="modal">
		<div class="body">
			body
		</div>
		<div class="btn_cancel" @click="modalToggle">
			<i class="icon icon-cancel" />
		</div>
	</div>
</template>

我使用v-if切换渲染,它适用于我在模态组件中创建的按钮。

但是我的问题是:我不知道如何使用父组件中的简单按钮切换它。我不知道如何从模态组件访问模态打开数据

好的,让我们试着做对。我建议制作一个成熟的组件,并使用父组件或其他包含中的 v 模型控制模态窗口的打开和关闭。

1( 我们需要在子组件的"props"中声明 prop - "值"。

<script>
export default {
name: 'Modal',
props: ["value"],
data() {
return {
modalOpen: true,
}
},
methods: {
modalToggle() {
this.modalOpen = !this.modalOpen
},
},
}
</script>

2( 替换您的"模态切换":

modalToggle() {
this.$emit('input', !this.value);
}

3( 在父组件或其他包含中声明"modal=false"var 并在组件上使用 v-model="modal" 和模态 var 的任何控制按钮。

总结

<template>
<div v-if="value" class="modal">
<div class="body">
body
</div>
<div class="btn_cancel" @click="modalToggle">
<i class="icon icon-cancel" />
</div>
</div>
</template>
<script>
export default {
name: "Modal",
props: ["value"],
methods: {
modalToggle() {
this.$emit("input", !this.value);
}
}
};
</script>

例:

Vue.component('modal', {
template: '<div v-if="value" class="modal"><div class="body">modal body</div><div class="btn_cancel" @click="modalToggle">close modal<i class="icon icon-cancel" /></div></div>',
props: ["value"],
	methods: {
		modalToggle() {
this.$emit('input', !this.value);
		}
	}
});
// create a new Vue instance and mount it to our div element above with the id of app
var vm = new Vue({
el: '#app',
data:() =>({
modal: false
}),
methods: {
openModal() {
this.modal = !this.modal;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div @click="openModal">Btn modal</div>

<modal v-model="modal"></modal>
</div>

使用您当前的实现,我建议您使用 refs https://v2.vuejs.org/v2/guide/components-edge-cases.html#Accessing-Child-Component-Instances-amp-Child-Elements

因此,在父组件中,将ref="child"添加到模态(子(组件,然后通过调用this.$refs.child.modalToggle()打开模态

  1. 您可以使用"激活器"插槽

  2. 您可以在子级上使用 ref="xxx" 并从父级访问它

最新更新