vue2.0 弹窗单独组件的开启关闭处理问题

vue2.0 弹窗单独组件的开启关闭处理问题

在某项目开发中有个需求将 element 弹窗组件单独写成一个组件进行复用
遇到问题,父传值默认open = false给子组件,点击事件开启父传值open= true,但是关闭时子组件需要open = false数值会改变,组件报错(vue的理念父传值给子,子不能修改数值)

解决方案:
通过 ref 获取子组件的事件进行组件内部操作改变数值
1.父组件名father.vue
2.子组件名children.vue
3.将子组件引入、注册、展示在父组件中
4.在子组件写一个开启弹窗方法,将弹窗组件开启的值改成true
showDialog(){
this.dialog = true
}
5.在父组件展示的子组件上加上 ref
6.在父组件的点击事件上调用子组件开启的方法 this.$refs.company.showDialog()
以上便可以成功的控制弹窗组件的开关了

//父页面father
<template>
	<div>
		<el-button type="text" size="small" @click="clickDetail">详情</el-button>
		<!-- 3.展示组件 -->
		<children ref="company"></children>
	</div>
</template>
<script>
	// 1.引入组件
	import children from '@/components/children'
	export default {
		name: 'father',
		//2.注册组件
		components: {
			children,
		},
		methods:{
			clickDetail() {
				this.$refs.company.showDialog()
			},
		}
	}
</script>
//子页面children
<template>
	<div class="InventoryDetail">
		<el-dialog title="提示" :visible.sync="dialog" width="30%">
			<span>这是一段信息</span>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialog = false">取 消</el-button>
				<el-button type="primary" @click="dialog = false">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>
<script>
	export default {
		name: 'InventoryDetail',
		data() {
			return {
				dialog: false,
			};
		},
		methods:{
			showDialog() {
				this.dialog = true
			}
		}
	}
</script>

版权声明:本文为weixin_45052308原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。