vue pass-by-value

1. Passing values ​​(props) between Vue parent and child components

First define a child component and register props
<template> in the component

<div>  
    <div>{{message}}(子组件)</div>  
</div>

</template> <script>

export default { props: { message: String //Define the type of passed value<br> } }

</script> <style> </style>

In the parent component, introduce the child component and pass in the required value in the child component

<template> <div>

    <div>父组件</div>  
    <child :message="parentMsg"></child>    
</div>  

</template>

<script>

import child from './child' //Introduce child component

export default {

data() {  
        return {  
            parentMsg: 'a message from parent'  //在data中定义需要传入的值
        }  
    },
    components: {  
        child  
    }

} </script>

<style> </style>

父组件向子组件传值成功
总结一下:
子组件在props中创建一个属性,用以接收父组件传过来的值
父组件中注册子组件
在子组件标签中添加子组件props中创建的属性
把需要传给子组件的值赋给该属性  

2. The child component passes the value to the parent component

1. Create a button in the child component, bind a click event to the button, use $emit to trigger a custom event in the function that responds to the click event, and pass a parameter <template>

**> <!--Create a button in the subcomponent and bind a click event to the button--> **

<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. Listen to the custom event in the child tag in the parent component and add a processing method that responds to the event

<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> > > The child component passed the value to the parent component successfully

in conclusion:

> > > 1、子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件  

> > > 2、将需要传的值作为$emit的第二个参数,该值将作为实参传给响应自定义事件的方法  

> > > 3、 在父组件中注册子组件并在子组件标签上绑定对自定义事件的监听  

> > > 4、在通信中,无论是子组件向父组件传值还是父组件向子组件传值,他们都有一个共同点就是有中间介质,子向父的介质是自定义事件,父向子的介质是props中的属性。抓准这两点对于父子通信就好理解了  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325331446&siteId=291194637