一、vue父子组件间传值(props)
先定义一个子组件,在组件中注册props
<template>
<div>
<div>{{message}}(子组件)</div>
</div>
</template> <script>
export default { props: { message: String //定义传值的类型<br> } }
</script> <style> </style>
在父组件中,引入子组件,并传入子组件内需要的值
<template> <div>
<div>父组件</div>
<child :message="parentMsg"></child>
</div>
</template>
<script>
import child from './child' //引入child组件
export default {
data() {
return {
parentMsg: 'a message from parent' //在data中定义需要传入的值 }
}, components: {
child
}
} </script>
<style> </style>
父组件向子组件传值成功
总结一下:
子组件在props中创建一个属性,用以接收父组件传过来的值
父组件中注册子组件
在子组件标签中添加子组件props中创建的属性
把需要传给子组件的值赋给该属性
二.子组件向父组件传值
1.在子组件中创建一个按钮,给按钮绑定一个点击事件,在响应该点击事件的函数中使用$emit来触发一个自定义事件,并传递一个参数 <template>
**> <!--在子组件中创建一个按钮,给按钮绑定一个点击事件--> **
<div>
<h2>child子组件部分</h2> <p>{{message}}</p> <button v-on:click="sendMsgToParent"></button>
</div>
</template>
<script> export default{ props:["message"], methods:{ sendMsgToParent:function(){ this.$emit("ListenToChlidEvent","this message from child"); } } } </script>
<style> </style>
2..在父组件中的子标签中监听该自定义事件并添加一个响应该事件的处理方法
<template>
<!--在父组件中引入子组件,并传入子组件内需要的值-->
<div>
<div>父组件</div>
<child v-bind:message="parentMsg" v-on:ListenToChlidEvent=""></child>
</div>
</template>
<script>
import child from './child' //引入child组件
export default{
data(){
return{
parentMsg:'我要吃肉肉'
}
},
components:{
child
},
methods:{
showMsgFromChild:function(data){
console.log(data);
}
},
}
</script>
<style>
</style> > > 子组件向父组件传值成功
总结一下:
> > > 1、子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件
> > > 2、将需要传的值作为$emit的第二个参数,该值将作为实参传给响应自定义事件的方法
> > > 3、 在父组件中注册子组件并在子组件标签上绑定对自定义事件的监听
> > > 4、在通信中,无论是子组件向父组件传值还是父组件向子组件传值,他们都有一个共同点就是有中间介质,子向父的介质是自定义事件,父向子的介质是props中的属性。抓准这两点对于父子通信就好理解了