VUE 父子组件的传递 props、$ref 、 $emit、$parent、$children、$root

原网站的网址:https://blog.csdn.net/alokka/article/details/87104189   非常详细的版本

看到别人的网页写的比较详细,就拿过来了。留着以后自己备用  哈哈哈

网页;https://blog.csdn.net/twodogya/article/details/80715049

一.父向子传递参数    继承的方式

     1.1 【父组件把(原始类型)传给子组件   :传递prop接收】      继承的方式

    父组件:<child   :childtraccept='fathertransform' ></childd>   

    子组件:prop:[ '','','']接收         

  1.2 【父组件把(方法)传给子组件          :传递prop接收】     继承的方式

    父组件把方法传递到子组件里面,子组件调用     问题:父组件如果有多个方法怎么办?

    父组件:<child :fatherMethod='fatherMethod'></child>   

    子组件:props:{

     fatherMethod: {

      type: Function,

      default: null }

       },

      methods:{

       childClick(){ this.fatherMethod() }

       }

  1.3 【父组件拿到子组件所有的值     $refs】  

    // ref 作用在组件上 指向的是组件的实例 实例上的方法都可以调用

    父组件:<child ref='child'></child>   

    父组件: console.log(this.$refs.child.msg)    或者  this.$refs.child.do()  

  1.3 【父组件拿到子组件所有的值    $children[0]

    // $children获取的是子组件的数组 通过索引找到对应的子组件的实例

    父组件:<child></child> 正常 引入 挂载  子组件        

      父组件:console.log(this.$children[0].msg)    或者  this.$children[0].childClick()   

     子组件:childClick(){

          this.$children.fatherMethod()

          console.log(this.$children.msg)

           }

二.子组件t向父传递参数,$emit有两种方式,

  2.1,【子组件把(原始类型)传给父组件  注意:函数+$emit传递函数+data接收】  带参数传递

    子组件 :this.$emit('tell',this.msg)               // 必须以函数的形式,向父组件派发事件+参数

     父组件:<child @tell='know'></child>    know(msg) { alert(msg); }     // // 父组件中 在子组件上监听子组件派发的tell方法 然后调用函数 就能调用子组件的原始数据

    带参数传递,参数是(子组件内容) -->要传递给父组件@接收内容->(父组件函数接收(data){ }data代表子组件的内容)   

  2.2,【子组件传把(方法)传到父组件,注意:函数+$emit传递函数接收】  不带参数传递

    子组件:this.$emit('tell')       // 函数+$emit传递  向父组件派发事件

    父组件:<child @tell='know'></child>      // 父组件中 在子组件上监听子组件派发的tell方法 然后调用函数 就能调用子组件的方法

     know(msg) { alert(msg); }

    不带参数传递,可以直接调用父组件函数(父组件函数接收)ChildClick(){  this.父组件函数()}    :                         

  2.3 【子组件获取所有父组件值   $parent】   

    组件通过$parent获取父组件的数据和方法   

    父组件:<child></child正常 引入 挂载  子组件

    子组件:childClick(){

       this.$parent.fatherMethod()

      console.log(this.$parent.msg)

     } 

注意:$root 和 $parent 都能够实现访问父组件的属性和方法,两者的区别在于,如果存在多级子组件,通过parent 访问得到的是它最近一级的父组件,通过root 访问得到的是根父组件(App.vue) 所以存在组件嵌套的情况下 不要使用 $root 

 父子传参:

                               

原文地址:https://www.cnblogs.com/maibao666/p/11344221.html