antd vue modal使用注意点

使用antd vue,当需要把modal封装成独立组件时,一般组件的显示与否是通过父组件传props过来,关闭再用this.$emit()传参给父组件做出相应变化。
父组件


<template>
	<a-button @click="showModal">show modal</a-button>
	<son-modal :visible="showModal" @cancel="handleCancel"></son-modal>
</template>

<script>
	import SonModal from './SonModal'
	export default{
		data(){
			return {
				showModal:false
			}
		},
		methods:{
			showModal(){
				this.showModal=true
			},
			handleCancel(){
				this.showModal=false
			}
		}
	}
</script>

子组件

<template>
	<a-modal :visible=visible @cancel="handleCancel"></a-modal>
</template>

<script>
	export default{
		props:{
			visible:{
				default:false
			}
		},
		methods:{
			handleCancel(){
				this.$emit('cancel')
			}
		}
	}
</script>

这种方式的话,点击modal右上角的X关闭时,会报错:
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop’s value. Prop being mutated: “visible”
**

解决办法:利用vue $refs实现

**
父组件


<template>
	<a-button @click="showModal">show modal</a-button>
	<son-modal ref="modal"></son-modal>
</template>

<script>
	import SonModal from './SonModal'
	export default{
		data(){
			return {}
		},
		methods:{
			showModal(){
				this.$refs.modal.show()
			}
		}
	}
</script>

子组件

<template>
	<a-modal :visible=visible @cancel="handleCancel"></a-modal>
</template>

<script>
	export default{
		data(){
			return{
				visible:false
			}
		},
		methods:{
			show(){
				this.visible=true
			},
			handleCancel(){
				this.visible=false
			}
		}
	}
</script>

你可能感兴趣的:(antd vue modal使用注意点)