vue2.x 父子组件传值

vue2.x父子组件传值方式

1.父传子:

1.1 父组件设置传递属性

<!-- 搜索组件 -->
    <Search 
        :searchInfo="searchInfo"  //父组件要传给子组件的值 "searchInfo"
    >
    </Search>

1.2 子组件通过props接收

<template>
    <div>
        //子组件通过props接收的是值,可以在子组件的模板中直接使用
       <div v-for="i in searchInfo" :key=i.id>
           <span>
               {{i.name}}
           </span>
       </div>
    </div>
</template>

<script>
export default {

      props: ["searchInfo"], //通过[]可以接收任意类型
  
      // 子组件通过props接收的是值,可以在子组件的钩子函数中直接用this使用

      created(){
        console.log(this.searchInfo)  
      }

 }

</script>

2.子传父

2.1 子组件通过this.$emit的方式传递给父组件

<template>
    <div>
        <button @click=handle(index,rows)>传递给父组件</button>
    </div>
</template>

<script>
export default {
    methods:{
        handle(index,rows){

           //通过this.$emit将operation已事件的方式传递给父组件,并将index,rows作为参数传递

           this.$emit("operation", index,rows); 
        }
    }
 }

</script>

2.2 父组件在标签上通过@xxx="xxx"接收

<template>
  <div>
    <!-- 搜索组件 -->
    //searchInfo为传递给子组件的属性
    //operation为子组件传递给父组件的属性
    <Search :searchInfo="searchInfo" @operation="operation"></Search>
  </div>
</template>

<script>
    export default {
        methods:{
           //子组件传递的事件在标签上接收之后可以在methods中直接调用
           //并可以拿到子组件的传递的参数index和rows

           operation(index, rows) {
                console.log(index,rows)
            }
        
        }
    }
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值