Vue第七讲

目录

vue各组件之间的传值

1.父组件向子组件传值

2.子组件向父组件传值

3.子组件之间的传值(兄弟组件)

4.无论嵌套多少层,子组件直接拿到父组件数据


vue各组件之间的传值


  • 1.父组件向子组件传值

方式一

父组件

<template> 
<First :poem="poem" type="诗词歌赋" />
</template>

子组件

export default{
      props:["poem","type"]
}

方式二

在子组件中直接获取父组件中的数据

mounted(){
    this.len = this.$parent.poems.length;
}

2.子组件向父组件传值

方式一

子组件

     methods:{
        addAuthor(){
           let obj={
                id:this.poem.id,
                author:this.author
            }
            // this.$emit(自定义事件类型,参数)
            this.$emit('aa',obj);
        }
    }

父组件

<template> 
<First @aa="addWriter" />
</template>

方式二

在父组件中使用$refs获取子组件中的值

<template> 
<First ref="first" />
<AA ref="aa"/>
</template> 
 
 mounted(){
    // $refs当前this的子组件
    console.log(this.$refs);
    let sum = 0;
    this.$refs.first.forEach(v=>{
      sum+=v.count;
    })
     sum+=this.$refs.aa.count;
     this.count=sum;
  },

3.任意组件之间的传值(可用于兄弟组件)

(1)在main.js中创建公共vue原型

Vue.prototype.$EventBus = new Vue()

兄弟一元素

 methods:{
        addAuthor(){
            // 发射事件 EventBus
            this.$EventBus.$emit("eb",this.poem.id);
       }
    }

兄弟二元素

 mounted(){
       // 实现 EventBus 的事件
        this.$EventBus.$on("eb",id=>{
            console.log("id === "+id);
        })
    }

4.无论嵌套多少层,子组件直接拿到根组件数据

  mounted(){
       console.log(this.root);
   }

猜你喜欢

转载自blog.csdn.net/weixin_52993364/article/details/125623811