vue3.0学习笔记 (组件之间的传递)

1.创建子组件和引入子组件

//父组件
<template>

    //子组件offSpring
    <offSpring></offSpring>

</template>

<script>

 //引入子组件    注意你引入子组件的位置
 import offSpringfrom './offSpring.vue'

 export default {
  
  //声明子组件
  components:{offSpring},

}
</script>




//offSpring子组件
<template>

<h2>姓名:</h2>

<h2>年龄:</h2>

</template>




不难看出  vue3.0与vue2.0的用法大致相同   注意setup函数就行

2.父组件传数据给子组件

//父组件传递
<template>

<offSpring :names='names' :age='age'></offSpring>

</template>

<script>

import offSpring from './offSpring.vue'

export default {

  components:{offSpring},

  setup(){

    let names='小张'

    let age =20


    return{

      names,

      age
    }
  }
}
</script>

//offSpring子组件接收
<template>

<!-- 子组件 -->
<h2>姓名:{{props.names}}</h2>

<h2>年龄:{{props.age}}</h2>

</template>

<script>


export default {

    props:['names','age'],

    setup(props){
        
        return{

            props,
            
        }
    }
}
</script>




3.子组件传数据给父组件

//子组件触发事件传递事件
<template>

<button @click="sayHelloClick">点击出现弹窗</button>
 
</template>

<script>



export default {
    
    //声明emits传的方法
    emits:['sayHelloClick'],

    setup(props,context){
        
        let childData='这是子组件传的数据'
        
    //借助context.emit传递出去'helloClick'是等下父组件自定义的方法,childData是要传的数据
        function sayHelloClick(){

           context.emit('helloClick',childData)

        }

        //别忘了  最后return出去
        return{

            sayHelloClick

        }
    }
}
</script>


//父组件接收子组件helloClick的自定义方法

<template>

<offSpring @helloClick='helloClick'></offSpring>

</template>

<script>

import offSpring from './offSpring.vue'

export default {

  components:{offSpring},

  setup(){

    function helloClick(value){

        alert(value)

    }

    return{

      helloClick,

    }
  }
}
</script>






4.setup接收的两个参数(props和centext)

// MyBook.vue
 
export default {
  setup(props, context) {
    // attrs对象 相当于2.0的this.$atters
    console.log(context.attrs)
 
    // 插槽      相当于vue2.0的this.$slots
    console.log(context.slots)
 
    // 触发事件  相当于vue2.0的this.$emit
    console.log(context.emit)
  }
}



//父组件插槽
<template>
<!-- 父组件 -->
<offSpring>

    <template v-slot:slotSpan>
      <span>插槽</span>
    </template>

</offSpring>
</template>



//子组件打印
<script>
export default {

    setup(props,context){

        console.log('插槽',context.slots)
       
    }
}
</script>

这是打印出来的效果

 props是父组件传过来的数据    centext有emit  slots  atters三大属性

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值