【Vue】父组件向子组件传递参数;子组件向父组件触发自定义事件
父组件向子组件传递参数
方法一:props
在 Vue 中,父组件向子组件传递数据主要通过props
来实现,以下是具体的步骤:
父组件中传递数据
在父组件中,当需要调用子组件 AddSampleDialog
时,通过 v-bind
或其缩写:
绑定要传递的数据。
- v-bind或其缩写
:
:用来动态的绑定一个或者多个属性,或者向另一个组件传递props值
假设要传递一个名为 sampleData
的对象数据给子组件,可以这样写:
<AddSampleDialog ref="addSampleDialog":title="sample_dialog_title":projectId="projectId":sample_form="sample_form"@newDataAdded="getSample"
></AddSampleDialog>
这里的sampleData
是父组件中的数据,可以是在data
函数中定义的,也可以是通过computed
计算属性得到的,或者是从接口获取到的数据等。
子组件中接收数据
在子组件AddSampleDialog
中,通过props
选项来接收父组件传递过来的数据。在AddSampleDialog
组件的script
部分,添加如下代码:
export default {name: 'AddSampleDialog',props: {sampleData: {type: Object, // 根据实际传递的数据类型进行修改required: true // 如果该数据是必须的,可以设置为true}},created() {console.log('接收到的数据:', this.sampleData);}
}
在上述代码中,props
定义了一个名为sampleData
的属性,指定了其数据类型为Object
,并在created
钩子函数中打印出接收到的数据,可以根据实际需求在子组件的其他地方使用该数据。
方法二:ref
在子组件AddSampleDialog
中的data函数中定义一个值 dialogVisible
,用于控制该子组件是否显示
data() {return {dialogVisible: false,}
}
在父组件中可以通过 ref 给子组件添加一个引用,父组件通过这个引用可以在JavaScript中直接访问该元素或者子组件
<AddSampleDialog ref="addSampleDialog":title="sample_dialog_title":projectId="projectId":sample_form="sample_form"@newDataAdded="getSample"
></AddSampleDialog>
在父组件的任何方法中可以通过 `this.$refs.addSampleDialog
这个引用,访问或修改子组件的属性 dialogVisible
showAddDialog() {this.$refs.addSampleDialog.dialogVisible = true;
},
子组件向父组件触发自定义事件
场景:新增信息子组件新增数据后,需要让父组件table获取最新数据
使用$emit和v-on
-
原理:子组件通过
$emit
向父组件触发一个自定义事件,并将新增的数据作为参数传递给父组件,父组件在模板中通过v-on
或其缩写$
监听该事件,在事件处理函数中更新table
的数据。 -
示例代码
-
子组件中触发事件:在
dialog
子组件中,当新增数据成功后,通过$emit
触发一个自定义事件newDataAdded
,并将新增的数据作为参数传递。 -
注意:newData作为参数可填可不填
-
this.$emit('newDataAdded', newData);
// or
this.$emit('newDataAdded');
-
父组件中监听事件并更新数据:在父组件的模板中,使用
v-on
监听dialog
子组件的newDataAdded
事件,在事件处理函数中更新table
的数据。
<template><div><table-component :data="tableData"></table-component><dialog-component @newDataAdded="handleNewDataAdded"></dialog-component></div>
</template>
<script>
import TableComponent from './TableComponent.vue';
import DialogComponent from './DialogComponent.vue';
export default {components: {TableComponent,DialogComponent},data() {return {tableData: []};},methods: {handleNewDataAdded(newData) {this.tableData.push(newData);}}
};
</script>