Vue组件传值,一之 父子之间如何传值?

Vue中组件之间是如何实现通信的?

  1、父传子:

    父传子父组件通过属性进行传值,子组件通过 props 进行接受;

 1 父组件中:
 2 
 3 <template>
 4     <div >
 5         我是父组件
 6         <Child :msg="info"/>
 7     </div>
 8 </template>
 9 <script>
10 import Child from './child';
11 export default {
12     data:function(){
13         return {
14             info:"时间是把杀猪刀"
15         }
16     },
17     components:{
18         Child
19     }
20 }
21 </script>

      props 接收值的方式有两中:一种是数组另一种是对象;

数组:虽然可以接收 props 传值但是不能定义传值的类型、默认值;
1 <template> 2 <div> 3 我是子组件 4 <p>我是接受到父组件传过来的值:{{msg}}</p> 5 </div> 6 </template> 7 <script> 8 export default { 9 props:['msg'], 10 data:function(){ 11 return { 12 13 } 14 } 15 } 16 </script>
对象:接收值的方式可以定义值的类型; 
1 <template> 2 <div> 3 我是子组件 4 <p>我是接受到父组件传过来的值:{{msg}}</p> 5 </div> 6 </template> 7 <script> 8 export default { 9 props:{ 10 msg: String 11 }, 12 data:function(){ 13 return { 14 15 } 16 } 17 } 18 </script>

  props 通过对象接收还可以定义其他东西,也可以利用这些来实现封装一些组件方便下次使用直接调用就好,下面来看一下:

 1  //必填的字符串
 2     props:{
 3         msg: {
 4             type: String,
 5             required: true
 6         }
 7     }
 8 // 带有默认值的数字
 9     props:{
10         msg: {
11             type: Number,
12             default: 100
13         }
14     }
15 // 带有默认值的对象
16     msg: {
17         type: Object,
18           // 对象或数组默认值必须从一个工厂函数获取
19             default: function () {
20                 return { message: 'hello world' }
21           }
22     }
23         

    props 更多使用方法可以参考官网: https://cn.vuejs.org/v2/guide/components-props.html 

  2、子传父:

    当子组件给父组件进行传值的时候,要在子组件标签内定义自定义方法 ( 注意自定义方法的函数不需要加( ) )

    在子组件内通过 this.$emit ( ) 触发这个方法; 参数1 是自定义的方法名称; 参数2 是需要传递的参数;

 1 父组件中:
 2 
 3 <template>
 4     <div >
 5         我是父组件
 6         <p>我是接收的子组件传过来的值:{{info}}</p>
13         <Child @sendInfo="getInfo"/>
14     </div>
15 </template>
16 <script>
17 import Child from './child';
18 export default {
19     data:function(){
20         return {
21             info:""
22         }
23     },
24     methods:{
25         getInfo(msg){
26             this.info = msg;
27         }
28     },
29     components:{
30         Child
31     }
32 }
33 </script>
子组件中:

<template>
    <div>
        我是子组件
        <button @click="handleClick">我要向父组件传值</button>
    </div>
</template>
<script>
export default {
    methods:{
        handleClick(){
            this.$emit('sendInfo','第二个参数写你要传递的内容')
        }
    }
}
</script>

  下一章推出非父子组件之间通信和如何利用原生JS实现$on、$emit、$off 来实现非父子组件之间的通信;