在vue-cli中如何实现子组件传值给父组件
下面通过一个小例子给大家演示一下
一、创建一个vue-cli项目
二、新建一个子组件son和一个父组件father
子组件son的代码如下:
<template>
<div class="son-container">
<h1>我是儿子</h1>
</div>
</template>
<script>
export default{
data(){
return{
send_value:"给爸爸的礼物"
}
},
created(){
this.$emit("give_father",this.send_value)
}
}
</script>
<style scoped>
.son-container{
width: 200px;
height: 200px;
background-color: red;
}
</style>
父组件的代码如下:
<template>
<div class="father-container">
<h1>我是爸爸</h1>
<son @give_father="get"></son>
<h3>{{from_son}}</h3>
</div>
</template>
<script>
import son from "@/components/son";
export default{
components:{
son
},
data(){
return{
from_son:""
}
},
methods:{
get(data){
console.log(data);
this.from_son = data
}
}
}
</script>
<style scoped>
.father-container{
width: 400px;
height: 400px;
background-color: green;
}
</style>
传递过程如下:
最后实现的效果:
好啦,本期知识点就到这里了,有疑问的小伙伴请在下方留言哦