vue中实现父子组件间单向数据流传递比较方便,子组件通过prop接收父组件传递过来的值,父组件通过监听子组件emit出的函数接收子组件传递的值。
1、父组件向子组件传值(prop)
父组件先绑定值modalVisible,子组件通过prop接收modalVisible
父组件:
<template>
<addModal :modalVisible="addModalVisible"></addModal>
</template>
<script>
export default {
data () {
return {
//模态框
addModalVisible: false,
}
},
}
</script>
子组件:
<script>
export default {
props: {
modalVisible: Boolean
},
}
每次父级组件发生更新时,子组件中所有的 prop 都将会刷新为最新的值,但是如果在子组件内部改变 prop,Vue 会在浏览器的控制台中发出警告:
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: "modalVisible"
在子组件中改变接收的prop值,vue文档提供了两种方式:https://cn.vuejs.org/v2/guide/components-props.html#%E5%8D%95%E5%90%91%E6%95%B0%E6%8D%AE%E6%B5%81
2、子组件向父组件传值
子组件通过emit,发布一个函数changeVisible,并携带false值,然后父组件监听到changeVisible函数,再函数中接收到子组件传递的false这个值
子组件:
<template>
<div>
<a-modal
:visible="modalVisible"
@cancel="handleCancel"
>
</a-modal>
</div>
</template>
<script>
export default {
name: 'addModal',
props: {
modalVisible: Boolean
},
methods: {
handleCancel(e) {
this.$emit('changeVisible',false)
},
}
}
父组件:
<template>
<a-button type="primary" @click="showModal">新建</a-button>
<addModal :modalVisible="addModalVisible"
v-on:changeVisible="changeVisible"
></addModal>
</template>
<script>
export default {
data () {
return {
//模态框
addModalVisible: false,
}
},
//模态框展示
changeVisible (value) {
this.addModalVisible = value;
},
}
3、父子组件相互传值
为实现父子组件相互传值,上述两个方法可以一起综合运用实现效果,但是vue中提供 修饰符sync ,以 update:propName 的模式触发事件达到父子组件相互传值,其中sync 会被扩展为一个自动更新父组件属性的 v-on 监听器。以父组件向子组件传递title这一propName为例:
子组件:
this.$emit('update:title', newTitle)
父组件:
<text-document v-bind:title.sync="title"></text-document>
//sync修饰符会被扩展为
<text-document v-bind:title="title" @update:title="val => title = newTitle"></text-document>
根据官网提供的父子组件值的双向传递方法,结合antdesign 模态框API方法,父组件通过:modalVisible.sync="addModalVisible"向子组件传递visible状态值,而子组件模态框关闭时会触发cancel事件,在其定义的handleCancel函数中使用 this.$emit('update:modalVisible',false)的模式触发事件向父组件传值,实现模态框的显示与隐藏。具体代码如下:
父组件:
<template>
<a-button type="primary" @click="showModal">新建</a-button>
<addModal :modalVisible.sync="addModalVisible"></addModal>
</template>
<script>
import addModal from './addModal.vue'
export default {
components: {
addModal
},
data () {
return {
//模态框
addModalVisible: false,
}
},
//模态框展示
showModal() {
this.addModalVisible = !this.addModalVisible;
},
}
子组件:
<template>
<a-modal
:visible="modalVisible"
@cancel="handleCancel"
>
</a-modal>
</template>
<script>
export default {
name: 'addModal',
props: {
modalVisible: Boolean
},
methods: {
handleCancel(e) {
this.$emit('update:modalVisible',false)
},
}
}
来源:oschina
链接:https://my.oschina.net/u/4131669/blog/3051839