vue中,父子组件传参的方法

2018-05-14  本文已影响0人  小虾米前端

1).$emit,这个就不用多说了,到哪儿都查的到。

2).如果不需要通过某事件触发,只把子组件中的参数传递到父组件,供父组件使用可以这样

父组件

<child :catchData="giveMeData"></child>    //引用子组件
data{
  return{
    fatherValue:""
  }
}
methods:{
  giveMeData(value){
    this.fatherValue=value     //在这里把子组件的参数赋值给父组件的参数
}
console.log( this.fatherValue)   //我是子组件的参数

子组件

data(){
  return{
    test:"我是子组件的参数"
  }
}
prop:['catchData']

mounted:{
  this.catchData(this.test)          //你需要传到父组件中的参数
}

3)$refs

  首先你的给子组件做标记。demo :<child ref="one"></child>

  然后在父组件中,通过this.$refs.one就可以访问了这个子组件了 ,包括访问子组件的data里面的数据,调用它的函数

4)$children

他返回的是一个组件集合,如果你能清楚的知道子组件的顺序,你也可以使用下标来操作;

for(let i=0;i<this.$children.length;i++){
       console.log(this.$children[i].msg);输出子组件的msg数据;
 }

上一篇 下一篇

猜你喜欢

热点阅读