父组件:Index.vue
<template>
<el-row>
<el-row>
<!-- 使用子组件 -->
<student ref="stuCom" :stu="stu" @callFunction="callFunction"></student>
</el-row>
<el-row>
<el-button @click="getStudent">父组件按钮</el-button>
</el-row>
</el-row>
</template>
<script>
// 引用子组件
import student from "../../components/student";
export default {
// 注册子组件
components: { student },
data() {
return {
stu: { name: "张三", address: "苏州" },
};
},
methods: {
// 接收子组件回调,并且接收参数
callFunction(item) {
console.log("接收子组件回调,并且接收参数");
console.log(item);
},
getStudent() {
// 调用子组件方法,并传参
this.$refs.stuCom.$emit("getStu", "张三");
// 获取子组件参数
this.stu = this.$refs.stuCom.item;
console.log("获取子组件参数");
console.log(this.stu);
},
},
mounted() {},
};
</script>
<style scoped>
</style>
子组件:student.vue
<template>
<el-row>
<!-- item和el控件双向绑定 -->
<el-input v-model="item.name"></el-input>
<el-input v-model="item.address"></el-input>
<el-button @click="callFunc">子组件按钮</el-button>
</el-row>
</template>
<script>
export default {
name: "student",
data() {
return {
item: {},
};
},
// 获取父组件传参
props: {
stu: { name: "", address: "" },
},
// 监听传参,赋值给item
watch: {
stu: {
immediate: true,
deep: true,
handler(newVal, oldVal) {
this.item = newVal;
},
},
},
methods: {
callFunc() {
// 调用父组件方法,并传参item
this.$emit("callFunction", this.item);
},
getStu(name) {
console.log("接收父组件调用,并且接收参数");
console.log(name);
},
},
mounted() {
// 监听父组件调用
this.$nextTick(function () {
this.$on("getStu", function (name) {
this.getStu(name);
});
});
},
};
</script>