当子组件有数据需要传递给父组件时,就需要进行子传父
一、使用步骤
1.子组件点击事件
2.子组件this.$emit发送父组件可以监听的数据
3.父组件监听子组件事件,并调用
4.处理数据
父组件代码
.<template>
<div class="father">
<h1>我是父组件</h1>
<!-- 渲染示例 -->
<h2>客户的名字是{{ userinfo.name }},年龄{{ userinfo.age }}</h2>
<!-- 步骤四:实现子传父:在父组件中使用子组件的位置,监听子组件所发出的事件
,并调用函数进行处理 -->
<son1 @getuser="dodo"></son1>
</div>
</template>
<script>
//引入组件
import son1 from "./son1";
export default {
//注册
components: {
son1,
},
data() {
return {
userinfo: "?",
};
},
methods: {
// 步骤五:在监听子组件发出事件的处理函数中,有一个默认的参数.
//就是子组件所传递的数据
dodo(data) {
console.log(data);
this.userinfo = data.user; //赋值给变量
},
},
};
</script>
.<style lang="less" scoped>
.father {
//添加样式区分
width: 100%;
background-color: cadetblue;
}
</style>
子组件代码
.<template>
<div class="son">
<h1>我是子组件</h1>
<!--示例渲染 -->
<h2>发送客户信息:{{ user.name }}{{ user.age }}</h2>
<!-- 步骤二:点击发送传递事件 -->
<button @click="senduser">按钮</button>
</div>
</template>
<script>
export default {
data() {
return {
//步骤一:准备发送的数据
user: {
name: "山竹",
age: 18,
},
};
},
methods: {
// 步骤三:通过$emit发送,带两个参数
// 语法:this.$emit(自定义事件类型,传输的数据)
senduser() {
this.$emit("getuser", { user: this.user });
//对象可以多传
},
},
};
</script>
.<style lang="less" scoped>
.son {
//添加样式区分
width: 80%;
background-color: cornflowerblue;
}
</style>
二、效果
三、子传父原理
四、常见问题
Error in v-on handler: “ReferenceError: data is not defined”
步骤三发送的时候使用v-on,这个问题可以看下是不是接受时参数没写,或发送时的参数错误
可以接受参数,可以打印,没报错,但是渲染不了,可能是调用数据结构有问题